Any way to prevent dynamic allocation of a class?

后端 未结 3 726
醉酒成梦
醉酒成梦 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:43

    Just make operator new private

    0 讨论(0)
  • 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<Base*>(&data[0]);
        ptr->~Base();
    }
    
    0 讨论(0)
  • 2021-01-18 06:50
    class A
    {
    private:
        void *operator new(size_t);
        ...
    };
    

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

    0 讨论(0)
提交回复
热议问题