How do I create a shared_ptr for a std :: vector?
What you are trying to do is let the smart pointer manipulate the stack object. This doesn't work as the stack object will kill itself when it goes out of scope. A smart pointer cannot prevent you from doing this.
std::shared_ptr<std::vector<uint8_t> > sp;
{
std::vector<uint8_t> mVector;
sp=std::shared_ptr<std::vector<uint8_t> >(&mVector);
}
sp->empty(); // dangling reference, as mVector is already destroyed
Three alternatives:
(1) Initialize the vector and let it be manipulated with shared_ptr
:
auto mSharedPtr = std::make_shared<std::vector<uint8_t> >(/* vector constructor arguments*/);
(2) Controlling a copy of a vector (by calling the vector copy constructor):
std::vector<uint8_t> mVector;
auto mSharedPtr = std::make_shared<std::vector<uint8_t> >(mVector);
(3) Move the vector (by calling the vector move constructor):
std::vector<uint8_t> mVector;
auto mSharedPtr = std::make_shared<std::vector<uint8_t> >(std::move(mVector));
//don't use mVector anymore.
source to share
First, what you are doing is very wrong, if you have specified a pointer to a shared_ptr make sure it is dynamically allocated new
and not on the stack. Otherwise, you can use a pointer instead of a shared_ptr.
Your code should be:
std::vector<uint8_t> mVector;
/* Copy the vector in a shared pointer */
std::shared_ptr<std::vector<uint8_t> > mSharedPtr ( new std::vector<uint8_t>(mVector) );
or
std::shared_ptr<std::vector<uint8_t> > mSharedPtr ( new std::vector<uint8_t>() );
As for why it won't compile, you need to use a constructor, not an operator =
.
As @remyabel pointed out, make_shared is more efficient:
std::vector<uint8_t> vector;
/* Copy the vector in a shared pointer */
auto sharedPtr = std::make_shared<std::vector<uint8_t>> (vector);
source to share