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)
The idea is to keep the new operator function private so that new cannot be called. See the following program. Objects of the 'Test' class cannot be created using new as new operator function is private in 'Test'. If we uncomment the 2nd line of main(), the program would produce a compile-time error.
First, overload the “new” operator in the class. So that, when we create object using “new”, it will not request memory from operating system but will call overloaded “new” method from the class itself for memory allocation. Make the overload new method private to make it in-accessible from outside of the class.
You can prevent an object being declared with automatic duration ("on the stack") by making its constructor private and providing a factory (abstract factory or factory method) to control creation of new objects.
Static memory allocation can only be done on stack whereas dynamic memory allocation can be done on both stack and heap. An example of dynamic allocation to be done on the stack is recursion where the functions are put into call stack in order of their occurrence and popped off one by one on reaching the base case.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With