ToB企服应用市场:ToB评测及商务社交产业平台

标题: [C++] std::optional与RVO:最高效的std::optional实践与探究 [打印本页]

作者: 美食家大橙子    时间: 2023-9-4 22:31
标题: [C++] std::optional与RVO:最高效的std::optional实践与探究
返回值优化RVO

在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




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4