c ++中的引用和析构函数

时间:2012-05-29 14:58:37

标签: c++ reference destructor

我有以下课程:

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();
   .....
}

为什么退出函数func时会调用B类的析构函数? Doest函数getB返回对象B的referance?如果类A仍然存在于函数func的末尾,为什么B的析构函数被调用?

2 个答案:

答案 0 :(得分:20)

 B b = a->getB();

将调用复制构造函数B(const& B),因此您在堆栈上创建一个新对象,其中包含引用返回的对象的副本。 改为使用:

 B& b = a->getB();

并且不会调用析构函数,因为您不会创建新的B对象

答案 1 :(得分:6)

当你有:

B b = a->getB();

BB)的现有实例的引用创建B&类型的新对象。这不是B::operator=,而是复制构造函数

每个类都有一个复制构造函数(如果你没有显式添加它,编译器会为你提供一个)。它接受一个参数,它是对同一个类的引用。您还没有在上面的代码中放置复制构造函数,所以我假设编译器为您生成了一个:

class B
{
public:
   B(B& other)
   {
      // memberwise copy (shallow copy) 
   };
};

所以A::getB()返回了对成员A::b的引用,并且此引用作为参数传递给B::B(B&)

void func()
{
   A *a = new A();  // Instance of A is created on the heap;
                    // (pointer a is a local variable and is on the stack though!)
                    // A::b is object of type B and it is on the heap as well  

   B b = a->getB(); // Instance of class B is created on the stack (local variable)
   .....
   delete a;        // deleting A from the heap: 
                    // A::~A is called which calls B::~B (of its member b)
} // a and b go out of the scope; b is an object => B::~B is called