Is it memory efficient to first create string and then add it to vector through move semantics or to create element in vector?
std::vector<std::string> v; v.push_back(""); v += 's'; v += 't'; v += 'r'; v.push_back(""); v += 's'; v += 't'; v += 'r';
std::vector<std::string> v; std::string s = ""; s += 's'; s += 't'; s += 'r'; std::string s1 = s; v.push_back(std::move(s)); v.push_back(std::move(s1));
In first case we first create element in vector and then modify it. I suppose in such small case there will be enough memory reserved in first place, but if it's not - will be vector v contiguous in memory, or just pointers to string objects? Does adding an element to string element in a vector makes last one to perform memory reallocation?
In second case, will be memory allocated for strings used as rvalue an added directly into allocated somewhere vector without memory reallocation for strings?
std::vector always stores data in a contiguous block of memory. In both cases if the strings You want to push back can't fit in the already allocated memory, there will be reallocation.
By doing v.push_back(std::move(s)) the data will be moved to the std::string in the vector from s, so the unused copy of s's data won't remain in the memory. This can be more efficient for large amount of data, but in Your case this won't make much difference.
In the second case You also have to initialize two more strings...