Search code examples
c++pointerscollectionsshared-ptr

Shared pointers to vectors


Please excuse the simple question, but I'm having trouble understanding pointers to collections.

Imagine that I have this vector of bytes:

vector<uint8_t> n;

I want to store this in a shared pointer. Why do I need the address-of (&) operator?

shared_ptr<vector<uint8_t>> m(&n);

I would think that the constructor would take n. But I also think that I have a deep misconception about what is going on here :)


Solution

  • I want to store this in a shared pointer.

    No you don't. A shared pointer is for managing a dynamic object that needs to be deleted; this vector wasn't created with new, so can't be managed by a (normal) shared pointer. The pointer would attempt to delete it, causing mayhem.

    You want to create the vector dynamically so that shared_ptr can manage it correctly:

    auto m = make_shared<vector<uint8_t>>();    
    

    Why do I need the address-of (&) operator?

    Because shared pointers are (usually) used to manage objects created with new, and new gives a pointer; so shared_ptr has a constructor taking a pointer argument. However, it's usually better to use the make_shared function demonstrated above, rather than messing around with new yourself.