c++11返回值优化还是搬家?

c++11 Return value optimization or move?(c++11返回值优化还是搬家?)
本文介绍了c++11返回值优化还是搬家?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 );
}

Which should I use?

解决方案

Use exclusively the first method:

Foo f()
{
  Foo result;
  mangle(result);
  return result;
}

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返回值优化还是搬家?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

What are access specifiers? Should I inherit with private, protected or public?(什么是访问说明符?我应该以私有、受保护还是公共继承?)
What does extern inline do?(外部内联做什么?)
Why can I use auto on a private type?(为什么我可以在私有类型上使用 auto ?)
Why cast unused return values to void?(为什么将未使用的返回值强制转换为 void?)
How to implement big int in C++(如何在 C++ 中实现大 int)
C++ template typedef(C++ 模板类型定义)