Any way to prevent dynamic allocation of a class?

后端 未结 3 728
醉酒成梦
醉酒成梦 2021-01-18 06:12

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 nee

3条回答
  •  执念已碎
    2021-01-18 06:45

    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(&data[0]);
        ptr->~Base();
    }
    

提交回复
热议问题