How do I create a vector of new'd vector pointers

Apr 24, 2013 at 4:58am
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?
Apr 24, 2013 at 5:06am
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?)
Apr 24, 2013 at 5:49am
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...
Last edited on Apr 24, 2013 at 5:51am
Apr 24, 2013 at 6:19am
Perhaps you could define a lambada function that returned a new'd object and just pass it in as the third argument to your for_each()?
Apr 24, 2013 at 6:32am
> Sure, but when you're creating pointers, whether smart or not, you still have to new the objects, right?

For std::unique_ptr<>, yes.
You just want to access the dynamically allocated object via a unique pointer; no overheads are involved.

For std::shared_ptr<>, typically no. You have to also create a shared reference count for the object.

std::shared_ptr<T> p { new T(1,2) } ; is typically less efficient (two dynamic memory allocations)

than std::shared_ptr<T> p { std::make_shared<T>(1,2) } ; (typically, a single dynamic memory allocation).

http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared

> 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.

Last edited on Apr 24, 2013 at 6:37am
Apr 24, 2013 at 7:30am
cire wrote:
My question is, why add 100 new'd elements to a vector? Why not just store them directly in the vector?
ausairman wrote:
Performance.

Mmm.. How does using new, which will require multiple dynamic allocations and deletions, gain you performance over something which does not?
Topic archived. No new replies allowed.