c ++ 11返回值优化或移动? [英] c++11 Return value optimization or move?

查看:115
本文介绍了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返回值优化或移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆