C++ c+中的引用和析构函数+;
我有以下课程:C++ c+中的引用和析构函数+;,c++,reference,destructor,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(); ..... } A类 { 公众: B&getB(){return B;} 私人:
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();
.....
}
A类
{
公众:
B&getB(){return B;}
私人:
B B;
};
B类
{
~B(){cout
将调用复制构造函数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&)
您的b对象仍然是函数的本地对象。引用的副本意味着b地址的副本?@chaiy不这么认为,您只需调用副本即可constructor@Shay不,这个答案有误导性。它意味着对象的副本。对不起,我不明白,如果调用了副本构造函数,那么通过引用返回与按值返回?复制构造函数仅在将返回的引用分配给实际对象时调用,如果将其分配给引用,则不会创建新对象。如果创建了新对象,则从函数中通过引用返回有什么用?@Shay:对象通过引用返回,因此它与通过val返回时一样保留对象的副本但是这个返回的引用随后被复制以在堆栈上创建一个新对象,然后使用返回的引用初始化该对象。
class B
{
public:
B(B& other)
{
// memberwise copy (shallow copy)
};
};
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