Reputation: 129
I'm wondering if I replace a dynamically allocated object in a vector with another, does the object get deleted or do I have to do it myself?
vector<thingamajig*> myvec;
...
myvec[17] = new thingamajig(paramsA);
...
myvec[17] = new thingamajig(paramsB); //what happens to the previous thingamajig?
Is this a memory leak? I don't understand vectors well enough to know if it'll delete thingamajig(paramsA) automatically or not. If not what is the proper way to clean the old one up?
Upvotes: 2
Views: 138
Reputation: 45410
what happens to the previous thingamajig
You lost the pointer to previous myvec[17]
thus causes memory leak.
You'd better use smart pointer in std::vector
#include <memory>
#include <vector>
std::vector<std::unique_ptr<thingamajig>> myvec;
myvec[17].reset(new thingamajig(paramsB));
Upvotes: 1