Nyaruko
Nyaruko

Reputation: 4459

c++ vector of pointers push back in different way

First we have a vector of pointers as:

vehicleGroup<vehicle*> VG;

In c++, is there a difference between:

VG.push_back(new vehicle(1));
VG.push_back(new vehicle(2));    

and

//tmp_vehicle is a public class member
tmp_vehicle = new vehicle(1);
VG.push_back(tmp_vehicle);
tmp_vehicle = new vehicle(2);
VG.push_back(tmp_vehicle);

Does the vecotr VG contains the address of pointer itself OR the address the pointer pointed to? What about map?

Upvotes: 1

Views: 2976

Answers (2)

myaut
myaut

Reputation: 11494

VG contains exactly what you ask it for - pointers to vehicle objects.

When you call push_back(), it takes object you provided (in your case "object" is vector*), makes copy of it and puts it to vector. Vector uses internal memory chunk where it stores objects, so that's why it needs to make copies.

Upvotes: 3

Mat
Mat

Reputation: 206679

The two versions do the same thing.

In your second version, tmp_vehicle first points to whatever new vehicule(1) returned. This pointer is then pushed into the vector, so the vector's first element now also points to that location.
Seen another way, you're not storing tmp_vehicule itself in the vector. You're storing a copy of that pointer.

Then you make tmp_vehicule point to something else. This doesn't change the fact that you stored a pointer to the first location in the vector. It changes what your variable points to, but doesn't change the vector in any way.

(And if you hadn't stored that pointer in the vector, you'd have a memory leak after the second assignment to tmp_vector, since you'd have lost all pointers to the first vehicule - so no way to delete it.)

Upvotes: 2

Related Questions