简体   繁体   中英

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?

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() ) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM