new operator and ownership

Jul 14, 2008 at 12:01pm
Dear all,
I'm a bit confused about new and delete operator and
when they go or not out of scope; So I have a couple of questions.

So let's start with the first one:

1) you have a class called city that has a method called CreateAGuy() that returns a people pointer:

1
2
3
people* city::CreateAGuy() { 
 // this method gives you back a _new_ people pointer
 return new people(); }


If I need to delete the people pointer, where and how should I do it?
Is it enough to delete it in this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
 * ...
 */
// the city
city *aCity = new city();
// a new guy
people* p = aCity->CreateAGuy();
/*
 * blah blah blah
 *  
 */

// time to clean up
delete p;
p = NULL;
/*
 * ...
 */


or should I take care of deleting it also inside the method?

2) now I create and use a std::vector of people:

1
2
3
4
5
6
7
// a collection of people
city* aCity = new city();
std::vector< people* > aLotOfPeople;
people* p;
for ( int i = 0; i < maxPeople; i++ ) {
  aLotOfPeople.push_back( aCity->CreateAGuy() );
}


Am I doubling the amount of allocated memory?
I mean: a memory location inside the method and one in the vector?

Is enough to clear memory in this way:

1
2
3
4
5
6
for ( int i = 0; i < maxPeople; i++ ) {
  p = aLotOfPeople[i];
  delete p;
  p = NULL;
}
aLotOfPeople.erase();


?

I hope it is clear enough.
Many thanks in advance!

Regards,
Marco
Jul 14, 2008 at 12:23pm
As a general rule, as long a you maintain a pointer to the new'd object, you can carry out a delete on that pointer any time you want. There is no concept of scope when associating new and delete.

Again with the the vector, you are maintaining a pointer inside the vector so you can run delete on them any time you want.

No you are not doubling the memory allocation. You are only running new once and then passing a copy of the subsequent pointer to the allocation, into the vector.
Yes it is enough to clear the memory in the way you describe for the vector and your second block of code is also OK.

Hope this helps
Last edited on Jul 14, 2008 at 12:26pm
Jul 14, 2008 at 1:42pm
It looks you addressed all my questions... great!

Thank you very much!

Regards,
Marco
Topic archived. No new replies allowed.