【问题标题】:Does the following code has undefined behavior due to r-value usage [duplicate]由于使用 r 值,以下代码是否具有未定义的行为 [重复]
【发布时间】:2016-11-19 16:14:51
【问题描述】:

根据帖子 r-value causes a warning without the use of std::move, 我想知道以下代码是否有未定义的行为:

struct Animal
{
  virtual void foo() const
  {
    std::cout << "error" << std::endl;
  }
};

struct Dog : public Animal
{
  void foo() const
  {
    std::cout << "wuff" << std::endl;
  }
};

struct A
{
  A( const Animal& a) : _a( a ) {}

  void foo()
  {
    _a.foo();
  }


  const Animal& _a;
};

int main()
{
  A a( Dog{} );
  a.foo();

}

在我的机器上,输出是(如预期的那样)wuff

【问题讨论】:

    标签: c++ class rvalue-reference


    【解决方案1】:

    确实,a.a_ 是语句a.foo(); 中的一个悬空引用,因此表达式_a.foo 的评估具有未定义的行为。临时对象Dog{} 的生命周期在完整表达式的末尾结束(并且没有延长)。

    【讨论】:

    • 您知道任何修复或解决方法吗?
    • @abraham_hilbert:通过 const 指针取值:A(const Animal* p) : a_(*p) {}。这使得不小心将纯右值的地址传入 变得更加困难。
    猜你喜欢
    • 2015-02-16
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 2018-01-29
    • 2015-07-30
    • 1970-01-01
    相关资源
    最近更新 更多