tags:

views:

56

answers:

3

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?

+2  A: 

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.

Steve Townsend
`shared_ptr` does not require C++0x; it is in TR1.
Potatoswatter
@Potatoswatter - thanks for the clarifying note - `unique_ptr` is a better fit to correct flawed `auto_ptr` semantics if OP has access to it.
Steve Townsend
+2  A: 

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

Armen Tsirunyan
A: 

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)

kkress
I would argue with your statement "Anything beyond this use is probably dangerous and/or broken"...
Armen Tsirunyan
Fair enough, there are other valid uses. Though auto_ptr's uses are relatively limited and it can be rather dangerous if you use it outside of a constrained scope, like as a local variable in a function.
kkress