私人析构函数 [英] Private destructor

查看:175
本文介绍了私人析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我可以在自由存储而不是堆栈上创建一个带有私有析构函数的类的对象?

Why can I create an object of a class with private destructor on free store but not on the stack ?

例如,这是非法的:

class Foo
{
public:
   explicit Foo( int );
   static void delete_foo(Foo* foo ) { delete foo; }
private:
   int x;
   ~Foo();
   Foo( const Foo& );
   Foo& operator=(const Foo& );
};

int main()
{
   Foo * fooptr = new Foo(5); // legal
   Foo::delete_foo( fooptr ); // legal 
   Foo foo(5); // illegal
}


推荐答案

它在栈上,它必须在函数可以返回之前被销毁。假设有问题的函数没有对析构函数的访问,这是不允许的。

When you create it on the stack, it must be destroyed before the function can return. Presuming the function in question does not have access to the destructor, this is not allowed.

当你在自由存储上创建它时,它留给其他代码,

When you create it on the free store, it is left for other code, which has access to the destructor, to destroy it.

具有私有析构函数的类的成员函数可以在堆栈上创建一个实例。甚至可以在没有预先存在的实例的情况下调用静态成员函数。可能没有很好的理由写这样的事情,虽然。

A member function of a class with a private destructor can create an instance on the stack. A static member function can even be called without a preexisting instance. There is probably no good reason to write such a thing, though.

这篇关于私人析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆