Can a call delete a pointer that is highlighted by a new placement?

Can I name a deletepointer that is placed with a placement new? If not, why? Please explain in detail.

I know that there is no room for deletion. But I wonder why just uninstalling the opetator fails to delete the memory without worrying about how the memory is allocated to which the pointer points are allocated?

delete does two things:

  • Call destrucor
  • Frees up memory

And I do not see the point of deleting, so that it is not possible to call any of these two operations on an object that was created using the new placement. Any idea on the reasons?

+5
source share
5

EDIT1: , . , delete opetator , , , ?

( , ), / :

  • new delete
  • new[] delete[] ( , , new new[])
  • malloc, free
  • CoTaskMemAlloc CoTaskMemFree
  • alloca ( )
  • MyCustomAllocator MyCustomFree

deallocator ( , seg fault now later). delete , - , new, .

, , . , - , , , . delete woul , : , new, . Kaboom.

, , , - , , . delete , , .

+4

delete , operator new. new , operator new, delete ( , ). new , - .

, delete , new, , new :

char* mem = new char[sizeof(MyObject)];
MyObject* o = new (mem) MyObject;

// use o

o->~MyObject(); // with placement new you have to call the destructor by yourself

delete[] mem;

:

char mem[16]; // create a buffer on the stack, assume sizeof(MyObject) == 16

MyObject* o = new (mem) MyObject; // use stack memory to hold a MyObject
                                  // note that after placement new is done, o == mem
                                  // pretend for this example that the point brought up by Martin in the comments didn't matter

delete o; // you just deleted memory in the stack! This is very bad

, delete , new. new , new, new, delete .

+7

, , , , , malloc() . . . ++.

+5

. -.

:

void * const addr = ::operator new(sizeof(T));  // get some memory

try {
  T * const pT = new (addr) T(args...);    // construct
  /* ... */
  p->~T();                                      // nap time
}
catch (...) {
}
::operator delete(addr);  // deallocate
                          // this is _operator_-delete, not a delete _expression_

, -new , void ::operator delete(void* [, size_t]) { }, no-op; , , T .

0

No, because the new placement does not allocate any memory. You are using a new placement in previously allocated raw memory. The only thing he does is call the constructor of the object.

0
source

All Articles