auto_ptr inside vector does not compile

J

Jarek Blakarz

Hi

I'm trying to compile the following program.
It does not compile.
Unfortunately I don't understand the compile error messages.
Please help me understanding what's going wrong and give me some indications of
how to fix it.

thanks

#include <memory>
#include <vector>
#include <iostream>
#include <string>

using namespace std;

class X {};

int main(void)
{
vector<auto_ptr<X> > vecXP;
auto_ptr<X> xPtr(new X);
vecXP . push_back(xPtr);

auto_ptr<auto_ptr<X> > elem = vecXP[0]; // compiler error

return 0;
}
 
S

SG

I'm trying to compile the following program.
It does not compile.
Unfortunately I don't understand the compile error messages.

which one?
Please help me understanding what's going wrong and give
me some indications of how to fix it.
  vector<auto_ptr<X> > vecXP;
  auto_ptr<X> xPtr(new X);
  vecXP . push_back(xPtr);
  auto_ptr<auto_ptr<X> > elem = vecXP[0];   // compiler error

auto_ptr has a destructive copy constructor and assignment operator
which is something that the standard containers have trouble dealing
with. Don't ever try to put an auto_ptr into a container. It just
won't work. Also, stop using auto_ptr altogether. As of C++11, it's
deprecated. Its replacement (unique_ptr) is much better behaved.

Cheers!
 
B

Balog Pal

I'm trying to compile the following program.
It does not compile.
Unfortunately I don't understand the compile error messages.
Please help me understanding what's going wrong and give me some indications of
how to fix it.

You shall read up on how to use the standard library. It's made up of
templates, but it imposes requirements on types to use them with. You
are responsible to obey the requirements, otherwise you face undefined
behavior. That can manifest at runtime, at compile time or whatever.

The types that you can use with standard collections must be assignable
and copyconstructible. That in practice means a copy of the type will be
equivalent to the original. For auto_ptr it is not true. So in short you
MUST NOT use auto_ptr in a std collection including vector.

Try some suitable smart pointer like shared_ptr (from C++11 or TR1 or if
you have neither from boost). That works fine in a vector.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

passing auto_ptr as shared_ptr 2
Marshalling auto_ptr/unique_ptr objects 1
auto_ptr 39
compile errors with list of auto_ptr 5
auto_ptr 18
Question on auto_ptr behavior 2
auto_ptr question 2
auto_ptr compile error 0

Members online

Forum statistics

Threads
473,961
Messages
2,570,131
Members
46,689
Latest member
liammiller

Latest Threads

Top