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?
3 Answers
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.

- 1
- 1

- 53,498
- 9
- 91
- 140
-
1`shared_ptr` does not require C++0x; it is in TR1. – Potatoswatter Oct 19 '10 at 19:19
-
@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 Oct 19 '10 at 19:22
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

- 1
- 1

- 130,161
- 59
- 324
- 434
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)

- 777
- 5
- 6
-
2I would argue with your statement "Anything beyond this use is probably dangerous and/or broken"... – Armen Tsirunyan Oct 19 '10 at 19:19
-
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 Oct 19 '10 at 19:25