Reputation: 4634
I am trying to create a bunch of shared pointers and put them into various containers.
Using raw pointers I would think to do the following:
Container a, b, c;
MyClass *ptr;
while(!finishedCreating){
ptr = new MyClass(SOME_CHANGING_THING);
a.add(ptr);
b.add(ptr);
c.add(ptr);
}
But of course now if I want to destruct a
, b
, and c
I would need to delete the pointers that they contain. If I did the following:
~Container{
delete[] myListOfPointers;
}
I would get an error when destructing because deleting a
would delete the same memory that b
and c
are supposed to get rid of.
Enter smart pointers, specifically, std::shared_ptr
. I would like to do something similar to before where I can create a single entity and use it to point to tons of memory locations but I'm not sure how to do this?
Would I want to create a pointer to a std::shared_ptr
so that I can reallocate that pointer such as
std::shared_ptr<MyClass> *ptr = new std::shared_ptr<MyClass>(new MyClass(THING));
Upvotes: 0
Views: 74
Reputation: 3778
shared_ptr
are here to allocate memory for you... Do not use new
with them !
The basic usage would be:
std::shared_ptr<MyClass> ptr(new MyClass(THING));
But even better:
auto ptr = std::make_shared<MyClass>(THING);
The latter provide a lot more guarantee over exception handling and also ensure you won't use new
anymore.
Your container will now be something like:
typedef std::vector<std::shared_ptr<MyClass>> Container;
For more information read shared_ptr on cppreference.
Upvotes: 7