By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,260 Members | 1,305 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,260 IT Pros & Developers. It's quick & easy.

vectors stl with pointers

P: n/a
hi all,
I have a simple question. I use a stl vector of pointers on objects of
my own class, say Person:
vector<Person*> vectPerson;
vectPerson.push_back(new Person("Sam"));

when I call vectPerson.pop_back, do i need to take care of the pointer
by calling delete or does the pop method handle this for me ?
thx
Sam
Jul 19 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
> when I call vectPerson.pop_back, do i need to take care of the pointer
by calling delete or does the pop method handle this for me ?

you will have to delete it on your own!

Jul 19 '05 #2

P: n/a
"berthelot samuel" <sa**************@voila.fr> wrote:
I have a simple question. I use a stl vector of pointers on objects of
my own class, say Person:
vector<Person*> vectPerson;
vectPerson.push_back(new Person("Sam"));

when I call vectPerson.pop_back, do i need to take care of the pointer
by calling delete or does the pop method handle this for me ?


No, you will have to do it yourself. The pop methods just remove the
pointer from the vector. The std::vector class cannot know if it has to
delete the object that is being referenced by the pointer; depending on
the situation it may or may not be the appropriate thing to do. Rather
than using raw pointers, you may also opt for putting boost::shared_ptr
of the boost library (http://www.boost.org/) in the vector. This way you
don't have to worry about ownership issues.

--
Peter van Merkerk
peter.van.merkerk(at)dse.nl
Jul 19 '05 #3

P: n/a

"berthelot samuel" <sa**************@voila.fr> wrote in message
news:ca************************@posting.google.com ...
hi all,
I have a simple question. I use a stl vector of pointers on objects of
my own class, say Person:
vector<Person*> vectPerson;
vectPerson.push_back(new Person("Sam"));

when I call vectPerson.pop_back, do i need to take care of the pointer
by calling delete or does the pop method handle this for me ?
thx
Sam


No you have to do it one your own, also you have to keep track of copies of
your vector.

This is why you shouldn't use raw pointers in an STL class (or anywhere
similar). Do yourself a favour and learn about smart pointers, will save you
months of debugging tricky pointer problems. Have a look at the smart_ptr
class from www.boost.org for instance, or get a good book.

john
Jul 19 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.