Calling delete on variable allocated on the stack

前端 未结 11 1916
遇见更好的自我
遇见更好的自我 2020-11-22 14:35

Ignoring programming style and design, is it \"safe\" to call delete on a variable allocated on the stack?

For example:

   int nAmount;
   delete &am         


        
11条回答
  •  伪装坚强ぢ
    2020-11-22 14:58

    Yes, it is undefined behavior: passing to delete anything that did not come from new is UB:

    C++ standard, section 3.7.3.2.3: The value of the first argument supplied to one of thea deallocation functions provided in the standard library may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call to the deallocation function has no effect. Otherwise, the value supplied to operator delete(void*) in the standard library shall be one of the values returned by a previous invocation of either operator new(std::size_t) or operator new(std::size_t, const std::nothrow_t&) in the standard library.

    The consequences of undefined behavior are, well, undefined. "Nothing happens" is as valid a consequence as anything else. However, it's usually "nothing happens right away": deallocating an invalid memory block may have severe consequences in subsequent calls to the allocator.

提交回复
热议问题