简体   繁体   中英

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));

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, ie 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.

When you create an object using the keyword new your allocating it on the heap. This will return a pointer to the object.

When as when you create an object without the keyword new it will get allocated on the stack and you will get access to that object in place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM