I need to create a shared_ptr to a std::vector, what is the correct syntax?
std::vector mVector;
shared_ptr> mSha
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<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 doesn't compile, you need to use the constructor, not the =
operator.
As pointed out by @remyabel, 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);
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<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 manage by the shared_ptr
:
auto mSharedPtr = std::make_shared<std::vector<uint8_t> >(/* vector constructor arguments*/);
(2) Manage a copy of the vector (by invoking the vector copy constructor):
std::vector<uint8_t> mVector;
auto mSharedPtr = std::make_shared<std::vector<uint8_t> >(mVector);
(3) Move the vector (by invoking 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.
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<std::vector<uint8_t>> sPtr (&mVector);
(2) using reset()
method of shared_ptr
std::shared_ptr<std::vector<uint8_t>> 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<std::vector<uint8_t>> sPtr (&mVector,[](std::vector<uint8_t>*){});