Jason S Jason S - 1 month ago 14
C++ Question

Any way to prevent dynamic allocation of a class?

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)

Answer

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();
}