samedi 2 avril 2016

how to move elements of an initializer_list?

Let's say you have a variable of type std::vector<std::string> and you initialize it with an initializer list:

using V = std::vector<std::string>;
V v = { "Hello", "little", "world", "of", "move", "semantics" };

The compiler will create a temporary std::string for each string literal, create an initializer list over these and then call the ctor for V and create the vector. The ctor does not know that all those strings are temporaries, so it is copying each string.

I haven't found anything in the standard which allows the vector ctor to move the elements when they are temporaries.

Am I missing something or does using initializer lists lead to unnecessary copies? I am writing classes where this problem could lead to significantly inefficient code. Any technique to avoid unnecessary copies would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire