Search⌘ K
AI Features

Be Careful With Braces When Returning

Explore how returning values with braces in C++17 affects move semantics, causing copies instead of moves. Understand the implications for types like std::unique_ptr, std::vector, and std::string, and learn to manage optional types effectively.

We'll cover the following...

You might be surprised by the following code:

C++ 17
#include <iostream>
#include <optional>
#include <string>
using namespace std;
std::optional<std::string> CreateString()
{
std::string str {"Hello Super Awesome Long String"};
return {str}; // this one will cause a copy
// return str; // this one moves
}
int main(){
std::optional<std::string> ostr = CreateString();
cout << *ostr << endl;
}

According to the Standard if you wrap a return value into braces {} then you prevent move operations from happening. The returned object will be copied only.

This is similar to the case with non-copyable types:

C++
std::unique_ptr<int> foo() {
std::unique_ptr<int> p;
return {p}; // uses copy of unique_ptr and so it breaks...
// return p; // this one moves, so it's fine with unique_ptr
}
...