简体   繁体   中英

C++ std::auto_ptr copy constructor

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?

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM