C ++,防止在堆栈上创建类实例(在编译期间) [英] C++, preventing class instance from being created on the stack (during compiltaion)

查看:170
本文介绍了C ++,防止在堆栈上创建类实例(在编译期间)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有些方法可以防止在堆上创建类,方法是阻止用户使用删除运算符。我试图做的正好相反。我有一个类,我想要阻止用户在堆栈上创建它的实例,并且只有使用 new 运算符发起的实例将编译。更具体地说,我想让下面的代码在编译期间接收错误:

  MyClass c1; //编译错误

MyClass * c1 = new MyClass(); // compiles okay



从搜索网页,我发现这个建议如何做: p>

  class MyClass {
public:
MyClass
private:
void destroy()const {delete this; }

...

private:
〜MyClass();
};

int main(int argc,char ** argv)
{
MyClass myclass; //< --- error,private destructor called here!

MyClass * myclass_ptr = new MyClass;
myclass_ptr-> destroy();
}

我不明白是为什么这应该工作。为什么在创建一个MyClass实例时调用析构函数?

解决方案 $ c>到达其范围的末尾(下一个} ),编译器调用析构函数将其从堆栈中释放。如果析构函数是私有的,那么析构函数不能被访问,所以类不能被放在堆栈上。



我不喜欢删除此。一般来说,我认为对象不应该销毁自己。也许一个更好的方法是为你的类拥有一个私有的构造函数,然后使用静态函数创建一个实例。

  //在类声明... 
static MyClass * Create()
{
return new MyClass(); //可以访问私有构造函数
}

// ...

MyClass myclass; //非法,不能访问私有构造函数

MyClass * pMyClass = MyClass :: Create();
delete pMyClass; // after usage


I know there are methods to prevent a class from being created on the heap, by preventing the user from using the new and delete operator. I am trying to do just the opposite. I have a class that I want to prevent the user from creating an instance of it on the stack, and that only instances instigated using the new operator will compile. More specifically, I want the following code to receive an error during compilation:

MyClass c1; //compilation error

MyClass* c1 = new MyClass(); //compiles okay

From searching the web, I found this suggestion on how to do it:

class MyClass {
public:
MyClass();
private:
void destroy() const { delete this; }

...

private:
~MyClass();
};

int main(int argc,char** argv)
{
    MyClass myclass; // <--- error, private destructor called here !!!

    MyClass* myclass_ptr = new MyClass;
    myclass_ptr->destroy();
}

What i don't understand is why this should work. Why would the destructor be called while creating an instance of MyClass?

解决方案

When myclass reaches the end of its scope (the next }) the compiler calls the destructor to free it from the stack. If the destructor is private, however, then the destructor cannot be accessed, so the class cannot be placed on the stack.

I don't like the look of delete this. In general I think objects should not destroy themselves. Perhaps a better way is to have a private constructor for your class then use a static function to create an instance.

// In class declaration...
static MyClass* Create()
{
    return new MyClass(); // can access private constructor
}

// ...

MyClass myclass; // illegal, cannot access private constructor

MyClass* pMyClass = MyClass::Create();
delete pMyClass; // after usage

这篇关于C ++,防止在堆栈上创建类实例(在编译期间)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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