2017-05-06 268 views
3

我有一個C++對象'bar',它存儲對象'foo'的引用。如果這個對象'foo'被銷燬:我的引用變得無效?這裏的例子:C++引用的生命週期

#include <iostream> 

struct Foo{ 
    int a = 5; 
}; 

class Bar{ 
    public: 
     Bar(const Foo &foo) : foo(foo){} 

     int getA() const{return foo.a;} 

    private: 
     const Foo &foo; 
}; 

int main(){ 
    Bar *bar; 
    { 
     Foo foo; 
     bar = new Bar(foo); 
    } //foo is destroyed. So, 'bar' contain an invalid ref to 'foo' ? 

    std::cout<<"A value: "<<bar->getA()<<std::endl; //is it correct to access to 'foo' ? 

    delete bar; 
    return 0; 
} 

該計劃似乎完全運行,Valgrind的沒有檢測到任何錯誤。這是對的嗎 ?

+0

正確的術語是「指針」;術語「引用」在C++中已經具有特定的技術含義,這與您的想法有所不同。 –

+2

@Kerrek說什麼? 'const Foo &foo;'是一個參考。 –

+0

@NeilButterworth:'bar'是一個指針;我指的是OP的陳述,即「酒吧存儲對象foo的引用」。相反,「bar存儲一個(未命名的)Bar對象的地址(它反過來就是一個引用)」的確,我可能一直在想OP以外的東西。 –

回答

1

C++中的引用不像託管內存語言中的引用。 當引用的對象死亡時,引用無效,並具有潛在的手榴彈行爲。