2
std::vector<int> myvec(){
  std::vector<int> myvector;

  // do some push_back's

  return myvector;
}

std::string mystr(){
  std::string mystring = "hello";

  return mystring;
}

std::vector<int> myvector = myvec();
std::string mystring = mystr();

Will it move? Or will it be copied by value?

Do not have anything else to say, but have to fulfil the requirement of writing more. Hence I am writing down some more text for you, folks

user3600124
  • 829
  • 1
  • 7
  • 19
  • 1
    Possible duplicate of [Returning std::vector by value](https://stackoverflow.com/questions/11247654/returning-stdvector-by-value) – Dan Jun 21 '17 at 10:21

2 Answers2

3

According to the C++ ISO standard, The compiler is allowed either to copy it, move it , or allocate it on the caller and avoid copying/moving altogether.

Most likely most of the compilers (GCC, Clang, VC++) will choose the third option (allocate it on the caller - Return Value Optimization) with optimizations turned on.

David Haim
  • 25,446
  • 3
  • 44
  • 78
-1

Depends on your version of C++, but in modern C++ there is a promise that returning an std:vector is efficient and doesn't cause an element-by-element copy operation.

Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18
  • Don't say modern C++. Say what standard version and ideally back it up with a reference or quote. – Brandin Jun 21 '17 at 10:46