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?

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
Anycorn
  • 50,217
  • 42
  • 167
  • 261

3 Answers3

3

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.

Community
  • 1
  • 1
Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
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

Community
  • 1
  • 1
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
1

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
  • 777
  • 5
  • 6
  • 2
    I 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