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;
}
...