c++11 Return value optimization or move?(c++11 返回值优化还是移动?)
问题描述
我不明白什么时候应该使用 std::move 以及什么时候应该让编译器优化...例如:
I don't understand when I should use std::move and when I should let the compiler optimize... for example:
using SerialBuffer = vector< unsigned char >;
// let compiler optimize it
SerialBuffer read( size_t size ) const
{
SerialBuffer buffer( size );
read( begin( buffer ), end( buffer ) );
// Return Value Optimization
return buffer;
}
// explicit move
SerialBuffer read( size_t size ) const
{
SerialBuffer buffer( size );
read( begin( buffer ), end( buffer ) );
return move( buffer );
}
我应该使用哪个?
推荐答案
只使用第一种方法:
Foo f()
{
Foo result;
mangle(result);
return result;
}
这将已经允许使用移动构造函数,如果有的话.事实上,当允许复制省略时,局部变量可以精确地绑定到 return 语句中的右值引用.
This will already allow the use of the move constructor, if one is available. In fact, a local variable can bind to an rvalue reference in a return statement precisely when copy elision is allowed.
您的第二个版本积极禁止复制省略.第一个版本普遍更好.
Your second version actively prohibits copy elision. The first version is universally better.
这篇关于c++11 返回值优化还是移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c++11 返回值优化还是移动?
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
