Why does return from a function not invoke move semantics in C++11? Problem with rvalue references
Hello! I started learning C++11 and move semantics, and I encountered a problem. I wrote a simple function that creates a vector and returns it:
```cpp
#include
#include
std::vector createVector() {
std::vector v = {1, 2, 3, 4, 5};
return v; // Hoping for move here
}
int main() {
std::vector result = createVector();
std::cout << "Size: " << result.size() << std::endl;
return 0;
}
```
I expected that the move constructor would be called on return to avoid copying. But when I read about rvalue references and move semantics, many say that the compiler decides what to do itself. I tried explicitly using std::move:
```cpp
return std::move(v);
```
But some say that this can even worsen the perfo
No answers yet.
Log in to leave an answer