在cppreference中,是这么介绍RVO的
In a return statement, when the operand is the name of a non-volatile object with automatic storage duration, which isn't a function parameter or a catch clause parameter, and which is of the same class type (ignoring cv-qualification) as the function return type. This variant of copy elision is known as NRVO, "named return value optimization."
即在返回函数内部临时变量(非函数参数,非catch参数)时,如果该参数的的类型和函数返回值类型相同,编译器就被允许去直接构造返回值(即使copy/move构造函数具有副作用)。
std::optional
std::optional是在C++17引入的,常用于有可能构造失败的函数,作为函数的返回值。
在cppreference中,std::optional的例子如下:
[code]#include #include #include // optional can be used as the return type of a factory that may failstd::optional create(bool b){ if (b) return "Godzilla"; return {};} // std::nullopt can be used to create any (empty) std::optionalauto create2(bool b){ return b ? std::optional{"Godzilla"} : std::nullopt;} int main(){ std::cout