开发者

auto_ptr released without assigning its return value

开发者 https://www.devze.com 2022-12-17 01:50 出处:网络
So what happens to a pointer if you release an object owned by auto_ptr but do not actually assign it to a raw pointer? It seems like it\'s supposed to be deleted but it never gets the chance to. So d

So what happens to a pointer if you release an object owned by auto_ptr but do not actually assign it to a raw pointer? It seems like it's supposed to be deleted but it never gets the chance to. So does it get leaked out "into the wild"?

void usin开发者_开发技巧gPointer(int* p); 

std::auto_ptr<int> point(new int);
*point = 3;

usingPointer(point.release());

Note: I don't use auto_ptr anymore, I use tr1::shared_ptr now. This situation just got me curious.


Unless usingPointer is calling delete on p, this is a memory leak. If you would call get instead of release then the memory will be automatically deleted when point falls out of scope.


release isn't suppose to delete the owned point, from the docs:

Sets the auto_ptr internal pointer to null pointer (which indicates it points to no object) without destructing the object currently pointed by the auto_ptr.

Also, it's overkill to replace all uses of your auto_ptr with tr1::shared_ptr - you should be using unique_ptr where a shared one isn't necessary.

0

精彩评论

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