Suppose we have a map of some complex objects, textures in my case.
std::map<unsigned int, Texture> _table;
What would be the most correct way to insert an object into such a map with a key which is obtained during the value (Texture) construction?
Say, we have:
Texture::Texture() { glGenTextures(1, &_id); }
Texture::~Texture() { glDeleteTextures(1, &_id); }
glGenTextures()
provides a new OpenGL ID into the _id
class data member.
glDeleteTextures()
releases resources and invalidates _id
.
So, I would like to avoid any intermediate objects and copying.
And after that I want to store this newly constructed texture in my _table.
Texture tex;
_table.insert({tex._id, tex});
I would prefer to use emplace here, but I'm not sure it is possible/safe to construct the texture and get the _id
to use for map insertion in the same line.
As for me, this looks like a pattern which should probably exist.
Otherwise, why should I not do anything like that?