Using the placement new syntax, I should be able to do something like this:
char *buffer = new char[sizeof(MyClass)]; //pre-allocated buffer
MyClass *my_class = new (buffer) MyClass; //put da class there
Now suppose I just do the first line, but not the second. Is there a way that it can be determined in code whether the buffer has been allocated appropriately, but no object of type MyClass has yet been instantiated there?
The language doesn't provide any built-in mechanism to provide that information, at least none that I know of. You'll have to add your own bookkeeping code to track such information.
For debugging purposes, you can add a special member signature
to MyClass
and set its value to a constant
class MyClass {
public:
MyClass() : signature(762347562374) {}
bool isValidSignature() const { return signature==762347562374; }
private:
unsigned long long signature;
<other members>
};
Then, check it as follows:
char *buffer = new char[sizeof(MyClass)]; //pre-allocated buffer
MyClass *my_class = new (buffer) MyClass; //put da class there
if (my_class->isValidSignature())
<this means that the object has been allocated correctly, with a high probability>
}
You can put everything that's related to signature, inside a proper #ifdef
so that is only runs in debug mode.
Original code:
char *buffer = new char[sizeof(MyClass)]; //pre-allocated buffer
MyClass *my_class = new (buffer) MyClass; //put da class there
To determine dynamically whether the placement new
has been performed information about it has to be stored somewhere. The language does not provide that service. So you have to do it yourself, in one of two possible main ways:
()
at the end of your new
expression. Otherwise there is no way to guarantee that the buffer contents don't look like an object. Two sub-cases:
bool
variable.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