开发者

smart pointer ( different between ~auto_ptr() and release() )

I would like to know the different between the ~auto_ptr() and release() functions.

Are they the sam开发者_开发技巧e method, or are there differences between the destruction and the release of the memory?


auto_ptr::release()

Sets the auto_ptr internal pointer to null pointer (which indicates it points to no object) without destructing the object currently pointed to by the auto_ptr. It returns the value of the internal pointer before it was set to null. After calling release() the auto_ptr can still be pointed to another object.

auto_ptr::~auto_ptr()

Deallocates the block of memory the object "points to" using delete and destructs the object.\After calling ~auto_ptr() the auto_ptr is destroyed and should not be used further.


Ehm... never call a destructor yourself, only if you allocated the space where the object resides with a placement new.
That said, the difference is, that release is valid and leaves the object in a valid state, with the possibility to accept another pointer.
~auto_ptr will destruct the object and leave it in an invalid state, using it after calling the destructor is undefined behaviour.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜