Reputation: 9380
I am aware that calling delete on a variable created using placement new and then accessing that block of memory has undefined behaviour.
int* x = new int[2];
char* ch = new(x) char();
*ch = 't';
delete ch;
But if the block of memory, instead of heap is allocated on stack and then we call delete on that variable and then access the memory, I get an exception that the block type is invalid.
int x[2];
char* ch = new(x) char();
*ch = 't';
delete ch;
So the list of questions is:
Upvotes: 7
Views: 1720
Reputation:
Is the exception due to call of delete on a stack?
Yes. Though to clarify a little, this is not a C++ exception. It is an error that is detected by runtime. If runtime is not that smart, you could as well run into undefined behavior.
Is it fine to use placement new on memory block on stack?
Yes. You might also take a look at alloca()
and Variable-length arrays (VLA) - those are another two mechanisms of allocating memory on stack. Note that VLA is part of C99 and not C++11 (and earlier) standards, but is supported by most production-grade compilers as an extension (it might appear in C++14).
If yes then how shall I delete the character pointer.
You should not. When you use a placement new, you do not call delete
, you simply invoke a destructor. For any given object o
of type T
you need to call o->~T();
instead of delete o;
. If you must, however, deal with the code that calls delete
or delete []
on such an object, you might need to overload operators delete
and delete[]
and make those operators do nothing (destructor is already ran at that point).
Is it possible to assign multiple variables on a single block of memory using placement new?
Yes. However, you need to take extra care to make sure you meet alignment requirements.
Upvotes: 17