Skip to content

Extending an element directly within a container – use return value of emplace_back

Simple adding without optimization:

std::vector<std::string> v;

std::string s1 = "Hello";
s1 += " - ";
s1 += "world";
v.emplace_back(s1);
// => requires copying of string
//    even when changing to move semantics a move operation would be necessary

Optimize with a simple trick – use return value of emplace_back:

auto& s2 = v.emplace_back("Hello");
s2 += " - ";
s2 += "world";
// => the string is created and extended directly within the vector
//    no copy or move is required