I need to create a shared_ptr to a std::vector, what is the correct syntax?
std::vector<uint8_t> mVector;
shared_ptr<std::vector<uint8_t>> mSharedPtr = &mVector;
The code above does not compile.
Thanks.
To assign a pointer to 'point to' an instance of an object use pointer = &vector_of_reviews . The & operator gets the address of something, and it's this that you want to assign to the pointer. *pointer = vector_of_reviews dereferences the pointer (obtains the actual object 'pointed to').
A null shared_ptr does serve the same purpose as a raw null pointer. It might indicate the non-availability of data. However, for the most part, there is no reason for a null shared_ptr to possess a control block or a managed nullptr .
A shared_ptr may share ownership of an object while storing a pointer to another object. get() returns the stored pointer, not the managed pointer.
The ownership of an object can only be shared with another shared_ptr by copy constructing or copy assigning its value to another shared_ptr . Constructing a new shared_ptr using the raw underlying pointer owned by another shared_ptr leads to undefined behavior.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With