Any way to prevent dynamic allocation of a class?

眉间皱痕 提交于 2019-12-01 15:56:06

问题


I'm using a C++ base class and subclasses (let's call them A and B for the sake of clarity) in my embedded system.

It's time- and space-critical, so I really need it to be kind of minimal.

The compiler complains about lack of a virtual destructor, which I understand, because that can get you into trouble if you allocate a B* and later delete the pointer as an instance of A*.

But I'm never going to allocate any instances of this class. Is there a way I can overload operator new() such that it compiles if there's no dynamic allocation of either class, but causes a compiler error if an end user tries to allocate new instances of A or B?

I'm looking for a similar approach to the common technique of "poisoning" automatic compiler copy constructors via private constructors. (e.g. http://channel9.msdn.com/Forums/TechOff/252214-Private-copy-constructor-and-private-operator-C)


回答1:


You can poison operator new in just the same way as you can a copy constructor. Just be sure not to poison placement new. A virtual destructor would still be a fine recommendation.

int main() {
    char data[sizeof(Derived)];
    if (condition)
        new (data) Derived();
    else
        new (data) Base();
    Base* ptr = reinterpret_cast<Base*>(&data[0]);
    ptr->~Base();
}



回答2:


class A
{
private:
    void *operator new(size_t);
    ...
};

The elipses are for the other overrides of operator new and the rest of the class.




回答3:


Just make operator new private



来源:https://stackoverflow.com/questions/6271615/any-way-to-prevent-dynamic-allocation-of-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!