1

Possible Duplicate:
C++ Vector Pointers to Objects
Does std::list::remove method call destructor of each removed element?

If I have a std::vector defined as:

std::vector<Object*>* myObjects;

And then call:

delete myObjects;

Will the elements in myObjects then also be deleted? Is there any difference using an std::array or any other stl container?

Thanks in advance

Community
  • 1
  • 1
  • 7
    Nope. This is why `std::unique_ptr<>` and `std::shared_ptr<>` exist. – ildjarn Jun 19 '12 at 17:20
  • And you also get undefined behaviour for `delete`ing an uninitialised variable, unless this variable is global or static in which case you're fine. – Seth Carnegie Jun 19 '12 at 17:26
  • 1
    I thought avoiding raw pointers is one of the benefits of using containers ... `std::vector myObjects;` or `std::vector> myObjects;` would be better ;-) – AJG85 Jun 19 '12 at 17:30
  • 1
    Why **would** anything get deleted? C++ isn't magic. It's *magical* perhaps, but it doesn't do just stuff behind your back. – Kerrek SB Jun 19 '12 at 17:46
  • I was really just wondering about the behaviour of vector – Fredrik Haikarainen Sep 23 '12 at 13:55

2 Answers2

6

No, and here's why.

Consider these two cases:

int a, b, c;

auto stackvec = new vector<int*> { &a, &b, &c };
auto heapvec  = new vector<int*> { new int, new int, new int };

delete stackvec;
delete heapvec;

If calling delete on the vector*s called delete on the pointers they hold, then you'd be in for a heap of trouble (pun intended) because you'd be deleteing automatic variables with the first delete which yields undefined behaviour (a bad thing).

You have to manually iterate the vector and delete the pointers yourself when you know they're dynamically allocated, or better, use std::unique_ptr and you never need to call delete on anything.

Also, you probably don't need a pointer to a vector in the first place, but I won't judge you since I don't know your situation.

As for std::array and std::vector, you need to know the size of your std::array at compile time and you can't resize it at runtime, but vector has neither of those restrictions.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
1
  1. No, you will have memory leaks.
  2. No, containers of pointers do not delete pointed objects.
    • Use Boost, it has containers of pointers which own the data.
    • boost::ptr_vector<int>
Martin York
  • 257,169
  • 86
  • 333
  • 562
Tomek
  • 4,554
  • 1
  • 19
  • 19