Sha*_*hay 8 c++ destructor reference
我有以下课程:
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();
.....
}
Run Code Online (Sandbox Code Playgroud)
为什么退出函数func时会调用B类的析构函数?Doest函数getB返回对象B的referance?如果类A仍然存在于函数func的末尾,为什么B的析构函数被调用?
lez*_*lon 21
B b = a->getB();
Run Code Online (Sandbox Code Playgroud)
将调用复制构造函数,B(const& B)
因此您在堆栈上创建一个新对象,它是引用返回的对象的副本.改为使用:
B& b = a->getB();
Run Code Online (Sandbox Code Playgroud)
并且不会调用析构函数,因为您不会创建新的B对象
当你有:
B b = a->getB();
Run Code Online (Sandbox Code Playgroud)
B
从对B
(B&
)的现有实例的引用创建一个新的类型对象.这不是在B::operator=
这里调用,而是复制构造函数.
每个类都有一个复制构造函数(如果你没有显式添加它,编译器会为你提供一个).它接受一个参数,它是对同一个类的引用.您还没有在上面的代码中放置复制构造函数,所以我假设编译器为您生成了一个:
class B
{
public:
B(B& other)
{
// memberwise copy (shallow copy)
};
};
Run Code Online (Sandbox Code Playgroud)
所以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
Run Code Online (Sandbox Code Playgroud)