Difference in std :: vector push_back (Object ()) and push_back (new object ())?

In my current code, I want to insert new DrawObjects into my vector,

std :: vector <DrawObject> objects;

What's the difference between:

objects.push_back(DrawObject(name, surfaceFile, xPos, yPos, willMoveVar, animationNumber)); 

and

 objects.push_back(new DrawObject(name, surfaceFile, xPos, yPos, willMoveVar, animationNumber)); 
+6
source share
4 answers

First, a non-pointer object is added, and the second adds a pointer to the vector. Thus, it all depends on the declaration of the vector as to what you should do.

In your case, since you declared objects as std::vector<DrawObject> , so the first one will work, since objects can store elements of type DrawObject , not DrawObject* .

In C ++ 11, you can use emplace_back as:

 objects.emplace_back(name, surfaceFile, xPos, yPos, willMoveVar, animationNumber); 

Pay attention to the difference. Compare this to:

 objects.push_back(DrawObject(name, surfaceFile, xPos, yPos, willMoveVar, animationNumber)); 

With emplace_back you do not create an object on the call site, instead you pass arguments to the vector, and the vector internally constructs the object in place. In some cases, it can be faster.

Read the emplace_back doc that says (underline mine)

Adds a new item to the end of the container. The element is built in place, i.e. Copy or move operations are not performed . The element constructor is called with exactly the same arguments that the function provides.

Since it avoids copying or moving, the resulting code may be slightly faster.

+11
source

Considering

 std::vector< DrawObject > objects; 

The difference between the two versions is that the first is correct, and the second is not.

If the second version compiles, as you indicate in the comments, it does not do what you expect from it. This also suggests that you should probably consider creating some DrawObject explicit constructors.

+1
source

The second version expects objects be a pointer vector for DrawObject, while the first expects objects to hold the objects themselves. Thus, depending on the declaration of objects only one of the versions will be compiled.

If you declare objects way you did this, only the first version will be compiled, if you declare objects as std::vector< DrawObject*> objects; , only the second version will be compiled.

+1
source

When you create an object using the new keyword, you allocate it in a heap. This will return a pointer to the object.

When you create an object without the new keyword, it will be allocated on the stack and you will get access to this object in place.

0
source

All Articles