我有一个类A,其中包含另一个类B的对象。这是一个私有(private)对象。但是,当我尝试使用 A 的对象访问 B 的成员变量时,不知何故调用了 B 的析构函数。 无法理解为什么 B 的析构函数在这里被调用?
以下代码的输出是:
In B ctor
In A ctor
10
In B dtor <------ Why this ?
In A dtor
In B dtor
代码示例:
#include "stdafx.h"
#include <iostream>
using namespace std;
//Implementaion of B class
class B
{
public:
int bVal1;
B::B(void)
{
cout << "In B ctor" << endl;
bVal1 = 10;
}
B::~B(void)
{
cout << "In B dtor" << endl;
}
};
//Implementaion of A class having private B's object ( composition )
class A
{
private:
B b;
public:
A::A(void)
{
cout << "In A ctor" << endl;
}
A::~A(void)
{
cout << "In A dtor" << endl;
}
B A::func2(void)
{
return b;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
A a; //ctor calling order : B followed by A
cout << a.func2().bVal1 << endl; //Why ADDITIONAL B's destructor is getting called here ???
return 0; //dtor calling order : A followed by B
}
对于这么长的代码,我深表歉意。
最佳答案
你的功能
B A::func2(void)
{
return b;
}
返回 B
类型对象的拷贝。所以你在 main()
函数中有一个临时的本地版本。所以 A::b
对象和临时 B
对象都被销毁了,因此你有 2 次调用 B::~B()
.
您的 main() 函数等同于此:
int _tmain(int argc, _TCHAR* argv[])
{
A a; //ctor calling order : B followed by A
B b = a.func2();
cout << b.bVal1 << endl; //Why ADDITIONAL B's destructor is getting called here ???
return 0; //dtor calling order : b, followed by A::b followed by followed by a
}
试试这样写:
const B& A::func2(void)
{
return b;
}
这只会给您调用 1 次 B::~B()
。
关于c++ - 在具有 'has-a' 关系的 C++ 类中两次调用析构函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30641799/