我有一个类型的析构函数已被显式删除;我想让该类型的一个实例成为另一个类的成员。
我的期望是,如果没有尝试删除包含类的实例(即,包含类的析构函数将无效),那应该没问题。
但是,当尝试实例化父类的构造函数时,clang (v3.3) 和 g++ (v 4.6.3) 都会出错。
例如:
class DeletedDtor
{
public:
DeletedDtor() {}
~DeletedDtor() = delete;
};
class MyClass
{
public:
MyClass() = default;
~MyClass() = delete;
private:
DeletedDtor a;
};
int main() {
MyClass *p = new MyClass();
}
在 g++ 下,这给出:
test.cpp: In function ‘int main()’:
test.cpp:19:30: error: use of deleted function ‘MyClass::MyClass()’
test.cpp:11:5: error: ‘MyClass::MyClass()’ is implicitly deleted because the default definition would be ill-formed:
test.cpp:11:5: error: use of deleted function ‘DeletedDtor::~DeletedDtor()’
test.cpp:5:5: error: declared here
自己定义 MyClass 构造函数,而不是让它采用默认实现,也无济于事:
class DeletedDtor
{
public:
DeletedDtor() {}
~DeletedDtor() = delete;
};
class MyClass
{
public:
MyClass();
~MyClass() = delete;
private:
DeletedDtor a;
};
MyClass::MyClass() : a() {}
int main() {
MyClass *p = new MyClass();
}
这给出了编译错误:
test2.cpp: In constructor ‘MyClass::MyClass()’:
test2.cpp:18:24: error: use of deleted function ‘DeletedDtor::~DeletedDtor()’
test2.cpp:5:5: error: declared here