We help IT Professionals succeed at work.
Get Started

best practices using a list of auto_ptr's?

TruthHunter asked
Last Modified: 2012-08-13

I have a question about "best practices" on how to implement a list of auto_ptr's that I'm hoping someone can help me with.

I have several classes derived from the same abstract base class, and I would like to keep pointers to the classes in some sort of container to easily traverse and invoke an inherited method within each.

The problem is I had wanted to wrap the pointers to the classes in auto_ptr's, but then I read a convincing article about why auto_ptr's should not be used in std containers:


So I'm left scratching my head and wondering what's the (best) solution?  Max points available!  Here's a quasi pseudo-code description of what I'm trying to do (this may not compile, it's just presented quickly to try to make the question clearer).

Thanks for any help!

class A
    virtual void F() = 0;

class B : public A
    virtual void F();

class C : public A
    virtual void F();

class D : public A
    virtual void F();

// Idea 1 - shouldn't do because no auto_ptr's in std
//          containers.
vector< auto_ptr< A > > v;
v.push_back( new B() );
v.push_back( new C() );
v.push_back( new D() );

for( int i = 0; i < v.size(); i++ )

// Idea 2 - simple array but isn't initializer behavior
//          unpredictable, if one of the new()'s fails?
auto_ptr< A > arr[3] = { new B(), new C(), new D() };

for( int j = 0; j < 3; j++ )

// Idea 3?

// Idea 4?

Open in new window

Watch Question
Senior Software Engineer (Avast)
This problem has been solved!
Unlock 3 Answers and 5 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE