Any way to prevent dynamic allocation of a class?

2020-04-03 12:34发布

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)

3条回答
霸刀☆藐视天下
2楼-- · 2020-04-03 13:15

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();
}
查看更多
放我归山
3楼-- · 2020-04-03 13:21

Just make operator new private

查看更多
一夜七次
4楼-- · 2020-04-03 13:23
class A
{
private:
    void *operator new(size_t);
    ...
};

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

查看更多
登录 后发表回答