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

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

    your code doesn't compile because you are assigning a raw pointer '&mVector' to smart pointer 'mSharedPtr' which are two different objects and no casting is allowed.

    you can do that by other approaches

    (1) intializing your shared_ptr with the raw pointer from the begining

    std::shared_ptr> sPtr (&mVector);
    

    (2) using reset() method of shared_ptr

    std::shared_ptr> sPtr;
    sPtr.reset(&mVector);
    

    assigning a stack object raw pointer to smart pointer , you should also supply an empty deleter to the smart pointer, so that the smart pointer doesn't delete the object when it is still on the stack.

    std::shared_ptr> sPtr (&mVector,[](std::vector*){});
    

提交回复
热议问题