I've recently discovered that I can call the destructor for a vector of pointers using this:
1 2
// call destructor of all pointers in this vector:
std::for_each(vec.begin(), vec.end(), std::default_delete<MyType>());
Now I'd like to know if I could do the same with emplace (or similar). Suppose I want to add 100 new'd elements to vec; can I do this without manually adding them?
I don't know how you store stuff in a vector manually.
My question is, why add 100 new'd elements to a vector? Why not just store them directly in the vector? Especially if the lifetime is tied to presence in the vector.
Might smart pointers be more appropriate than calling std::for_each to delete vector items (which I assume you then need to remove from the vector?)
I don't know how you store stuff in a vector manually.
1 2 3 4
vector<int> myvec;
myvec.reserve(100);
for (int i = 0; i!=100; ++i)
myvec.push_back(i);
My question is, why add 100 new'd elements to a vector? Why not just store them directly in the vector?
Performance.
Might smart pointers be more appropriate than calling std::for_each to delete vector items (which I assume you then need to remove from the vector?)
Sure, but when you're creating pointers, whether smart or not, you still have to new the objects, right? I'm new to smart pointers so I might be wrong about all this...
> Might smart pointers be more appropriate than calling std::for_each to delete vector items
YES. I would go as far as to say: in most contexts, creating a situation where one has to call std::for_each to delete each object is an avoidable technical error.