2016-11-19 45 views
-3

根据岗位 r-value causes a warning without the use of std::move, 如果下面的代码是未定义行为,我想知道:是否将下面的代码是未定义行为,由于R值使用

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

回答

4

事实上,a.a_是陈述a.foo();中的悬挂参考,因此表达式_a.foo的评估具有未定义的行为。临时对象Dog{}的生命周期在完整表达式的末尾结束(并且是而不是扩展)。

+0

你知道任何修复或解决方法吗? –

+0

@abraham_hilbert:通过const指针取得值:'A(const Animal * p):a _(* p){}'。这使得它更难以无意中通过prvalue的地址。 –

相关问题