How can I create a shared_ptr to a std::vector?

后端 未结 3 1075
一生所求
一生所求 2021-02-01 09:05

I need to create a shared_ptr to a std::vector, what is the correct syntax?

std::vector mVector;
shared_ptr> mSha         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 09:17

    First, what you're doing is very wrong, if you give a pointer to a shared_ptr make sure it's dynamically allocated with new, not on the stack. Otherwise you may just as well use a pointer instead of a shared_ptr.

    Your code should be:

    std::vector mVector;
    /* Copy the vector in a shared pointer */
    std::shared_ptr > mSharedPtr ( new std::vector(mVector) );
    

    or:

    std::shared_ptr > mSharedPtr ( new std::vector() );
    

    As for why it doesn't compile, you need to use the constructor, not the = operator.

    As pointed out by @remyabel, make_shared is more efficient:

    std::vector vector;
    /* Copy the vector in a shared pointer */
    auto sharedPtr = std::make_shared> (vector);
    

提交回复
热议问题