vectors stl with pointers

B

berthelot samuel

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
 
P

Patrik Stellmann

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!
 
P

Peter van Merkerk

berthelot samuel said:
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.
 
J

John Harrison

berthelot samuel said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top