John John - 1 year ago 70
C++ Question

What is the correct way to create an object and push it in a vector?

What is the correct way to add an object to a vector ? It seems that a vector takes a copy of the object, rather than the actual object...

For example:

class MyClass{
void addATexture(int textureWidth,int textureHeight){
Texture tex(textureWidth,textureHeight);
_textures.push_back(tex);//A copy of tex is pushed into in..
} // ---> At this point, tex is destroyed...

What is the correct way to put objects in the vector, without copies ?

Answer Source

If you are using C++11 or later, you may want to use emplace_back to create an object in place:

_textures.emplace_back(textureWidth, textureHeight);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download