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++
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
