简体   繁体   English

是否可以在堆上强制 C++ 类实例化?

[英]Is it possible to force c++ class instantiation on the heap?

I need to use this class in a threaded application so instantiating it on the stack will obviously be a problem, is there a way to force new to be used when instantiating the class?我需要在线程应用程序中使用这个class ,所以在堆栈上实例化它显然是一个问题,有没有办法在实例化类时强制使用new

I have made the constructors private and the new operator public, something like我已将构造函数private ,将new运算符设为公有,例如

public:
    void *operator new(size_t);

private:
    SomeClass(void);
    SomeClass(SomeType value); 
               .
               .
               .

but as I expected when using但正如我在使用时预期的那样

SomeClass *heapInstance = new SomeClass(value);

the compiler tells me that the constructor is private.编译器告诉我构造函数是私有的。

Question :问题

  • Is there a solution to this?这个问题有方法解决吗?

Note : I have used this class all over the place, and now I need to fix my code, ie I need the compiler to prevent compilation so I don't need to manually search for each occurrence, I am not very good at c++ I just had to use it because I needed to do a GUI cross platform application and picked Qt for several reasons which are irrelevant here.注意:我到处都使用这个class ,现在我需要修复我的代码,即我需要编译器来阻止编译所以我不需要手动搜索每次出现,我不太擅长 c++ 我只是不得不使用它,因为我需要做一个 GUI 跨平台应用程序,并出于几个与此无关的原因选择了Qt

Just make ctor private/protected and provide a static method(s) to create an instance:只需将 ctor 设为私有/受保护并提供静态方法来创建实例:

class HeapOnly {
     HeapOnly();
     HeapOnly( int i );
public:
     static HeapOnly *create() { return new HeapOnly; }
     static HeapOnly *create( int i ) { return new HeapOnly( i ); }
};

You may consider to return a std::unique_ptr in general case, but for Qt that could be not necessary.在一般情况下,您可以考虑返回std::unique_ptr ,但对于 Qt 而言,这可能不是必需的。

This will not solve your problem instantly, but you will get compile error everywhere where instance is created and you can replace them by create function call catching places where class instance created on a stack.这不会立即解决您的问题,但是在创建实例的任何地方都会出现编译错误,您可以通过创建函数调用来替换它们,以捕获在堆栈上创建类实例的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM