Any way to prevent dynamic allocation of a class?

余生颓废 提交于 2019-12-01 16:37:05

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();
}
class A
{
private:
    void *operator new(size_t);
    ...
};

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

Just make operator new private

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