[C++] std::optional与RVO:最高效的std::optional实践与探究

美食家大橙子  金牌会员 | 2023-9-4 22:31:53 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 891|帖子 891|积分 2673

返回值优化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
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

美食家大橙子

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表