what happens when a container of pointers is destroyed, are pointers destroyed?
Just a simple question: If I create something like:
std::string my_function()
{
std::vector<some_pointer*> pVec;
pVec.push_back(new some_pointer);
pVec.push_back(new some_pointer);
pVec.push_back(new some_pointer);
<some action that uses pVec and produces a std::string result>
return result;
}
When pVec goes out of scope, what happens to the pointers? Are they destroyed too?
No. The container won't destroy them; you'll have to destroy them yourself or use a container of smart pointers.
Thanks again Si,
I was worried about this; I think that I'll try to use smart pointers as you suggest, it seems a safe and reliable approach.
I was worried about this; I think that I'll try to use smart pointers as you suggest, it seems a safe and reliable approach.
Just to clarify some terminology the pointers are destroyed, its the pointed at things which aren't destroyed. (sorry, it just seems people mix the two together all the time)
... But please, first be sure that you can't (and know why not) just simplify:
std::string my_function(){std::vector<some_class> vec;vec.push_back(some_class());vec.push_back(some_class());vec.push_back(some_class());<some action that uses vec and produces a std::string result>return result;}
Hi Zahlman,
I don't have a choice (I don't think). I typically avoid pointers like the plague, but in this case I need dynamic allocation because I will load data files that may vary in size between runs and need to size the vector dynamically at runtime.
I don't have a choice (I don't think). I typically avoid pointers like the plague, but in this case I need dynamic allocation because I will load data files that may vary in size between runs and need to size the vector dynamically at runtime.
That doesn't mean you need to use pointers -- you're probably thinking of how you'd have to handle it if you didn't have vector. vector's resizable; this will work fine:
If you don't know the size beforehand, it will still work, you will just have to omit the reserve() call which will cause a (entirely trivial here) perf issue since more reallocations of the underlying memory will occur.
int count = readNumberOfThingsFromFile();std::vector<Thing> things; // No pointers!things.reserve(count);for(int i = 0; i < count; ++i){ Thing thing = readThingFromFile(); things.push_back(thing);}
If you don't know the size beforehand, it will still work, you will just have to omit the reserve() call which will cause a (entirely trivial here) perf issue since more reallocations of the underlying memory will occur.
if you still want to use pointers in a vector, have a look at boost::ptr_vector, it will call delete on pointers when being destructed.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement