Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference and destructor in c++

I have the following class:

class A
{
public:
   B& getB() {return b;}    
private:   
    B b;
};

class B
{
   ~B() {cout<<"destructor B is called";}
...

};

void func()
{
   A *a = new a;
   B b = a->getB();
   .....
}

Why does the destructor of class B is called when exiting the function func? Doest the function getB return a referance to the object B? if class A still exists at the end of function func, why does the destructor of B is called?

like image 791
Shay Avatar asked May 29 '12 14:05

Shay


1 Answers

 B b = a->getB();

will be calling the copy constructor B(const& B) so you are creating a new object on the stack with is a copy of the object returned by the reference. Use instead:

 B& b = a->getB();

and no destructor will be called since you won't create a new B object

like image 104
lezebulon Avatar answered Oct 18 '22 21:10

lezebulon