Understanding return value optimization and returning temporaries - C++(了解返回值优化和返回临时值 - C++)
问题描述
请考虑这三个功能.
std::string get_a_string()
{
return "hello";
}
std::string get_a_string1()
{
return std::string("hello");
}
std::string get_a_string2()
{
std::string str("hello");
return str;
}
- RVO 是否适用于所有三种情况?
- 可以像上面的代码那样返回一个临时的吗?我相信这没问题,因为我是按值返回它,而不是返回对它的任何引用.
有什么想法吗?
推荐答案
在前两种情况下,将进行 RVO 优化.RVO 是旧功能,大多数编译器都支持它.最后一种情况就是所谓的 NRVO(命名为 RVO).这是 C++ 相对较新的特性.标准允许但不要求实现 NRVO(以及 RVO),但一些编译器支持它.
In two first cases RVO optimization will take place. RVO is old feature and most compilers supports it. The last case is so called NRVO (Named RVO). That's relatively new feature of C++. Standard allows, but doesn't require implementation of NRVO (as well as RVO), but some compilers supports it.
您可以在 Scott Meyers 的书 更有效的 C++.35 种改进程序和设计的新方法.
You could read more about RVO in Item 20 of Scott Meyers book More Effective C++. 35 New Ways to Improve Your Programs and Designs.
这里是一篇关于Visual C++ 2005 中的 NRVO.
Here is a good article about NRVO in Visual C++ 2005.
这篇关于了解返回值优化和返回临时值 - C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:了解返回值优化和返回临时值 - C++


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09