使用私有析构函数删除对象
在下面的代码中怎么可能允许使用私有析构函数删除对象?我已将实际程序简化为以下示例,但它仍然可以编译并运行。
class SomeClass;
int main(int argc, char *argv[])
{
SomeClass* boo = 0; // in real program it will be valid pointer
delete boo; // how it can work?
return -1;
}
class SomeClass
{
private:
~SomeClass() {}; // ! private destructor !
};
How is that possible that it is allowed to delete object with private destructor in the following code? I've reduced real program to the following sample, but it still compiles and works.
class SomeClass;
int main(int argc, char *argv[])
{
SomeClass* boo = 0; // in real program it will be valid pointer
delete boo; // how it can work?
return -1;
}
class SomeClass
{
private:
~SomeClass() {}; // ! private destructor !
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在尝试删除不完整类类型的对象。 C++ 标准表示在这种情况下您将得到未定义的行为 (5.3.5/5):
要检测此类情况,您可以使用
boost::checked_delete< /代码>
:
You are trying to delete object of incomplete class type. C++ Standard says that you'll get undefined behavior in this case (5.3.5/5):
To detect such cases you could use
boost::checked_delete
:此代码会导致未定义的行为 (UB)。
删除
具有非平凡析构函数的不完整类型的对象是 C++ 中的 UB。在您的代码中,类型SomeClass
在删除时不完整,并且它有一个不平凡的析构函数。编译器通常会对此发出警告,因为在 C++ 中,这并不违反约束条件。因此,严格来说,您的代码无法“工作”。它只是简单地编译并在运行时执行一些未定义的操作。
只是编译器不需要捕获此错误。这样做的原因是,如果您的对象有一个简单的析构函数,那么这可能完全没问题。编译器无法知道该类型最终将具有什么样的析构函数,因此无法确定这是否是错误。
This code causes undefined behavior (UB). It is UB in C++ to
delete
an object of incomplete type having a non-trivial destructor. And in your code the typeSomeClass
is incomplete at the point ofdelete
, and it has a non-trivial destructor. Compilers usually issue a warning about this, since in C++ formally this is not a constraint violation.So, strictly speaking, your code doesn't "work". It simply compiles and does something undefined when run.
The compiler is just not required to catch this error. The reason for this is that this could be perfectly fine if your object has a trivial destructor. The compiler has no way of knowing what kind of destructor this type will eventually have, so it can't say for sure whether this is an error or not.
因为调用
operator delete
时,SomeClass
类型没有完全声明。删除这样的指针是未定义的行为,但实际上大多数编译器只会释放内存(如果指针为非 NULL)而不调用析构函数。
例如,g++ 会向您发出有关此问题的警告:
Because
SomeClass
type is not completely declared when invokingoperator delete
.Deleting such a pointer is undefined behavior, but in practice most compilers would just free the memory (if the pointer was non-NULL) and not call the destructor.
For example, g++ will give you a warning about this issue: