Subway
Subway

Reputation: 5716

c++: Initialize vector of shared_ptr in constructor as different pointers

Here is what I have:

class A
{
    A(int i):_i(i){}

private:
    int _i;
};

class B
{
    B();

private:
    std::vector< boost::shared_ptr<A> > _v;
}

And I need to initialized _v with two boost::shared_ptr<A>s.

I tried this:

B::B():_v(2, boost::make_shared<A>(0)){}

But it seems that both pointer point to the sole created object - not what I need.

I don't have c++11 so I can't use:

B::B():_v{boost::make_shared<A>(0), boost::make_shared<A>(0)}{}

What is the best solution for this situation?

Upvotes: 1

Views: 2480

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275220

Move the creation of the vector into a function that returns a vector.

The cost of copying a vector of shared_ptr with 2 elements is going to be low enough that you won't care, and with NRVO and RVO it could be completely optimized out even in C++03. (In C++11, if NRVO and RVO are blocked for whatever reason, it will only do moves).

 // if you make it a member, make it `static`:
 std::vector<boost::shared_ptr<A> > make_vector() {
    std::vector<boost::shared_ptr<A> > retval;
    retval.push_back( boost::make_shared<A>(0) );
    retval.push_back( boost::make_shared<A>(0) );
    return retval;
 }
 B::B():_v( make_vector() ) {}

Upvotes: 2

Related Questions