John John - 13 days ago 4
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{
private:
std::vector<Texture>_textures;
public:
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

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