basics/motiv11.cpp

The following code example is taken from the book
C++ Move Semantics - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2020
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

#include <string>
#include <vector>

std::vector<std::string> createAndInsert()
{
  std::vector<std::string> coll;  // create vector of strings
  coll.reserve(3);                // reserve memory for 3 elements
  std::string s = "data";         // create string object

  coll.push_back(s);              // insert string object
  coll.push_back(s+s);            // insert temporary string
  coll.push_back(std::move(s));   // insert string (we no longer need the value of s)

  return coll;                    // return vector of strings
}

int main()
{
  std::vector<std::string> v;     // create empty vector of strings
  //...
  v = createAndInsert();          // assign returned vector of strings
  //...
}