Delete when posting new

I know that calling delete on a variable created using the new placement and then accessing this memory block has undefined behavior.

int* x = new int[2]; char* ch = new(x) char(); *ch = 't'; delete ch; 

But if the memory block instead of the heap is allocated on the stack, and then we call delete on this variable and then access the memory, I get an exception that the type is invalid .

 int x[2]; char* ch = new(x) char(); *ch = 't'; delete ch; 

So, a list of questions:

  • Is an exception caused by calling delete on the stack?
  • Can I use a new placement in a memory block on the stack?
  • If so, then how do I remove a character pointer.
  • Is it possible to assign several variables on the same memory block using a new location?
+7
c ++
source share
1 answer

Is an exception caused by calling delete on the stack?

Yes. Although to clarify a bit, this is not an exception to C ++. This is a runtime error. If the runtime is not so smart, you may also encounter undefined behavior.

Can I use a new placement in a memory block on the stack?

Yes. You can also take a look at alloca() and Variable Length Arrays (VLA) - these are two more mechanisms for allocating memory on the stack. Note that VLA is part of the C99 standards, not C ++ 11 (and earlier), but is supported by most production-class compilers as an extension (it may appear in C ++ 14).

If so, how should I remove the character pointer.

You should not. When you use a new placement, you are not calling delete , you are just calling the destructor. For any given object o type T you need to call o->~T(); instead of delete o; . However, if you have to deal with code that calls delete or delete [] on such an object, you may need to overload the delete and delete[] statements and make these statements do nothing (the destructor is already running at that point).

Is it possible to assign several variables in one memory block using the new allocation?

Yes. However, you must take extra care to ensure that you meet the alignment requirements .

+16
source share

All Articles