You are not logged in.
Pages: 1
I'm reading a piece of C++ code, and I found an unusual syntax for the new operator:
new (ptr) MyClass();
where ptr is a pointer and MyClass() the default constructor of a certain class. I searched the web to find what this is supposed to do, but I found nothing. My guess is that new creates a MyClass instance at the memory address specified by ptr; in other words, that no memory allocation is done since ptr has to point to an already allocated memory bunch. Am I right?
Thank you
Offline
Your guess is correct.
It's called "placement new". More info under http://www.devx.com/tips/Tip/12582
Offline
Thank you very much, ber_t. So I guess that there's no check on the fact that objects put in place can fit inside the allocated memory? In other words, if I allocate space for 10 chars and then do a placement new for a string with 20 chars what would happen? A segmentation violation or something similar?
Offline
Yeah you'd get undefined behaviour, so don't do that . In fact, there's no way it could check, 'cause the pointer you give it could be from malloc(), on the stack, in a global variable, or an mmap'ed file, etc.
The other important thing to know is that there's no "placement delete" syntax, so you can't do "delete (ptr) ptr;" or anything similar. Instead, you call the destructor directly, i.e. "ptr->~MyClass();", and this is basically the only time you'll ever do that.
Offline
The other important thing to know is that there's no "placement delete" syntax, so you can't do "delete (ptr) ptr;" or anything similar. Instead, you call the destructor directly, i.e. "ptr->~MyClass();", and this is basically the only time you'll ever do that.
Thanks, I didn't think about this!
Could I, for example, do this if I want also to free the memory:
MyClass *dummyPtr = ptr;
delete dummyPtr;
dummyPtr = ptr = NULL;
This way delete should be aware that the object at memory location given by ptr is of MyClass type, and should correctly destroy it and free the memory. This obviously if the original allocated area size was sizeof(MyClass)...
Offline
Nope you couldn't do that, because "delete" only works on memory allocated by the regular (non-placement) operator new. So if it was allocated by malloc(), mmap(), or something else, delete will do the wrong thing. If the memory was originally allocated by operator new(), then that would work, but be careful:
char *ptr = new char[sizeof(MyClass)];
MyClass *dummyPtr = new(static_cast<void*>(ptr)) MyClass();
delete dummyPtr;
won't work because ptr was allocated with operator new[], which needs to be matched by an operator delete[] (on a pointer to type with the same size as the objects in the initial allocation, too).
Offline
Ok, thanks a lot. I think I understand the point, now.
Offline
Pages: 1