考虑这段代码:拷贝构造
#include <vector>
#include <iostream>
using namespace std;
class Base
{
char _type;
public:
Base(char type):
_type(type)
{}
~Base() {
cout << "Base destructor: " << _type << endl;
}
};
class uncopyable
{
protected:
uncopyable() {}
~uncopyable() {}
private:
uncopyable(const uncopyable&);
const uncopyable& operator=(const uncopyable&);
};
class Child : public Base, private uncopyable
{
int j;
public:
Child():
Base('c')
{}
~Child() {
cout << "Child destructor" << endl;
}
};
int main()
{
vector<Base> v;
Base b('b');
Child c;
v.push_back(b);
v.push_back(c);
return 0;
}
我的系统上的输出是:
Base destructor: b
Child destructor
Base destructor: c
Base destructor: b
Base destructor: b
Base destructor: c
我的问题是:
为什么是
Base
(类型b)的析构函数被调用三次而不是两次(我们是否有超过两个对象b的副本)?当我们复制一个类型为
Child
的对象时,考虑到其父类的副本构造函数是私有的,会发生什么情况。它是不确定的行为?无论何时我试图复制
Child
类型的对象,我都希望得到编译时错误。我认为孩子的默认拷贝构造函数会尝试调用Uncopyable类的私有拷贝构造函数并导致编译错误。为什么它不给编译错误?
代码被这样设计的原因是因为Child
类是巨大的。
当客户端试图复制一个Child
对象(调用Child
的析构函数而不调用Base
的析构函数)时,所需的行为是抛弃子数据。
这段代码实现了这一点,但我想它会导致未定义的行为并且有内存泄漏(从未调用复制实例的Child
的析构函数)。
你想要一个'编译时'错误还是你想扔掉孩子的数据?这些是相互矛盾的陈述,除非我错过了一些东西。 – Chip
@Chip修复它。谢谢。 –