C++ std::auto_ptr copy constructor

守給你的承諾、 提交于 2019-12-10 23:14:06

问题


std::auto_ptr lacks const copy constructor, therefore I cannot use it directly in collections. is there some way to have for example vector of std::auto_ptr without using boost pointer collection template?


回答1:


If you have a C++0x compiler you can use shared_ptr or unique_ptr as appropriate.

There is a good example of correct unique_ptr usage here courtesy of @James McNellis. For a shared_ptr walkthrough look here, courtesy of @D.Shawley. [Upvotes would still be appreciated on those threads, I am sure.]

vector of auto_ptr is always invalid, although Visual C++ v6 disagreed.




回答2:


No, you just can't have a vector of std::auto_ptr, though there exist many speculations that you can. But if your compiler supports C++0x, you can use std::unique_ptr, which is the new alternative of the deprecated auto pointer which, quote from the new standard, provides a superior alternative. See also this thread




回答3:


auto_ptr is designed for auto deletion when a variable leaves scope. You don't want to use it in a collection, instead as mentioned above you want to use something like shared_ptr.

Example of auto_ptr's typical use:

void foo()
{
   auto_ptr<int> bar = auto_ptr<int>(new int);
   ...

   return;  //memory held by auto_ptr is automatically deleted
}

Anything beyond this use is potentially dangerous and/or broken if you are not sure of the special semantics of auto_ptr. (Edit: clarify based on Armen's comment)



来源:https://stackoverflow.com/questions/3971818/c-stdauto-ptr-copy-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!