push_back a pointer

Nov 22, 2012 at 1:00pm
Hi,

I wanted to know if there's something wrong with this code:
1
2
3
4
5
6
7
vector<Course*> vec;
while(something)
{
   ...
   Course* c = new Course();
   vec.push_back(c);
}


when the loop is done c is deleted , but vec's elements still point to the object created on the heap,right?
Last edited on Nov 22, 2012 at 1:01pm
Nov 22, 2012 at 1:07pm
vec.end() is an iterator 'pointing' to one past the last element.

If the vector is not empty, & *(vec.end()-1) would point to a pointer (the value_type is a pointer to Course) to the last object created on the heap.

If Course is not a polymorphic type, consider using value semantics instead:
1
2
3
4
5
6
7
8
vector<Course> vec;
while(something)
{
   ...
   Course c ;
   // ...
   vec.push_back(c);
}

Nov 22, 2012 at 2:04pm
First of all, thnx!
I want to see if I understood correctly
1
2
3
4
5
6
7
vector<Course*> vec;
while(something)
{
   ...
   Course* c = new CScourse(); //correction
   vec.push_back(c);
}

in this case vec[i] would point to a pointer to an object on the heap?

1
2
3
4
5
6
7
vector<Course*> vec;
while(something)
{
   ...
   Course* c = new CScourse();
   vec.push_back(&(*c));
}

would vec[i] point to an object on the heap now?
Nov 22, 2012 at 2:30pm
vector<Course*> vec;
In this case, an item in the vector - vec[i] - would be a pointer.
1
2
3
   Course* c = new CScourse(); //correction
   vec.push_back(c);
   assert( vec.back() == c ) ; // the vector holds a copy of the pointer 

And an iterator - vec.begin() - would 'point' to the pointer.

&(*c) == c ;

1
2
3
4
5
int object = 78 ;
int* pointer = &object ; // pointer holds the address of the object
int& reference = *pointer ; // dereference the pointer and we get an alias for the object
int* another_pointer = &reference ; // another_pointer == pointer
assert( &*pointer == pointer ) ; 
Last edited on Nov 22, 2012 at 2:31pm
Topic archived. No new replies allowed.