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

后端 未结 3 1069
一生所求
一生所求 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:28

    What you are trying to do is to let a smart pointer manage a stack object. This doesn't work, as the stack object is going to kill itself when it goes out of scope. The smart pointer can't prevent it from doing this.

    std::shared_ptr > sp;
    {
       std::vector mVector;
       sp=std::shared_ptr >(&mVector);
    }
    sp->empty();   // dangling reference, as mVector is already destroyed
    

    Three alternatives:

    (1) Initialize the vector and let it manage by the shared_ptr:

    auto mSharedPtr = std::make_shared >(/* vector constructor arguments*/);
    


    (2) Manage a copy of the vector (by invoking the vector copy constructor):

    std::vector mVector;
    auto mSharedPtr = std::make_shared >(mVector);
    


    (3) Move the vector (by invoking the vector move constructor):

    std::vector mVector;
    auto mSharedPtr = std::make_shared >(std::move(mVector));
    //don't use mVector anymore.
    

提交回复
热议问题