I need to create a shared_ptr to a std::vector, what is the correct syntax?
std::vector mVector;
shared_ptr> mSha
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.