...

/

Be Careful With Braces When Returning

Be Careful With Braces When Returning

Let's observe some seemingly ordinary code and understand why it can potentially be harmful.

We'll cover the following...

You might be surprised by the following code:

Press + to interact
#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:

Press + to interact
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
}
...