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

5
  • 7
    Nope. This is why std::unique_ptr<> and std::shared_ptr<> exist. Commented Jun 19, 2012 at 17:20
  • And you also get undefined behaviour for deleteing an uninitialised variable, unless this variable is global or static in which case you're fine. Commented Jun 19, 2012 at 17:26
  • 1
    I thought avoiding raw pointers is one of the benefits of using containers ... std::vector<Object> myObjects; or std::vector<std::shared_ptr<Object>> myObjects; would be better ;-) Commented Jun 19, 2012 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. Commented Jun 19, 2012 at 17:46
  • I was really just wondering about the behaviour of vector Commented Sep 23, 2012 at 13:55

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.