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

reference and destructor in c++

本文关键字:析构函数 引用 C++      更新时间:2023-10-16

我有以下类:

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

为什么在退出函数函数时调用类 B 的析构函数?是否让函数 getB 返回对对象 B 的引用?如果类 A 在函数函数的末尾仍然存在,为什么调用 B 的析构函数?

 B b = a->getB();

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

 B& b = a->getB();

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

当你有:

B b = a->getB();

B 的现有实例 (B& ) 的引用创建类型 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