Search code examples
c++heap-memorynew-operatordelete-operatorstack-memory

Using new operator to statically allocate an object


Of course the next should not be done although it is valid for the compiler. But what is happening when you do?

CClass clss = *new CClass();

On the contrary to the above, the next does compile but gives an assertion error.

delete &clss;

Does this have something to do with allocating memory on either the stack or the heap?


Solution

  • The first line of code is correct, you initialize a statically allocated CClass instance with an another instance dynamically allocated.

    The second is obviously wrong as you try to delete an object that has not been dynamically allocated .

    The first line produces a memory leak because you dynamically allocate a bunch of memory but never retain its address, so it can never be deallocated (deleted).