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));
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With