Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference on std::vector push_back(Object()) and push_back(new Object())?

In my current code, I'm wanting to insert new DrawObjects into a vector I created,

std::vector< DrawObject > objects;

What is 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));
like image 993
parreirat Avatar asked Jan 05 '13 19:01

parreirat


3 Answers

First one adds non-pointer object, while the second one adds pointer to the vector. So it all depends on the declaration of the vector as to which one you should do.

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

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

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

Note the difference. Compare it with:

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

With emplace_back, you don't construct the object at the call-site, instead you pass the arguments to vector, and the vector internally constructs the object in place. In some cases, this could be faster.

Read the doc about emplace_back which says (emphasize mine),

Appends a new element to the end of the container. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element is called with exactly the same arguments that are supplied to the function.

As it avoids copy or move, the resultant code could be a bit faster.

like image 77
Nawaz Avatar answered Oct 03 '22 19:10

Nawaz


Given

std::vector< DrawObject > objects;

The difference between the two versions is that the first one is correct, and the second one isn't.

If the second version compiles, as you indicate in the comments, it doesn't do what you expect it might. It also suggests that you should probably consider making some of DrawObject's constructors explicit.

like image 42
NPE Avatar answered Oct 03 '22 19:10

NPE


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

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

like image 44
Ivaylo Strandjev Avatar answered Oct 03 '22 20:10

Ivaylo Strandjev