c++ 返回空对象_C++核心准则ES.56?:只在将对象移到其他作用域时使用move?操作

a7456f8c56b844ee089ec7a108f6b4eb.png

ES.56: Write std::move() only when you need to explicitly move an object to another scope

ES.56:只在需要将一个对象显式移动到另外的作用域时使用std::move

Reason(原因)

We move, rather than copy, to avoid duplication and for improved performance.

我们使用move而不是copy是为了避免不必要的重复并提高性能。

A move typically leaves behind an empty object (C.64), which can be surprising or even dangerous, so we try to avoid moving from lvalues (they might be accessed later).

移动操作一般会留下一个空对象(C.64),它可能引起误解甚至危险。因此我们努力避免移动左值(它们可能在后续代码中被使用)。

Notes(注意)

Moving is done implicitly when the source is an rvalue (e.g., value in a return treatment or a function result), so don't pointlessly complicate code in those cases by writing move explicitly. Instead, write short functions that return values, and both the function's return and the caller's accepting of the return will be optimized naturally.

如果源数据是右值,移动操作会隐式进行(例如return处理或函数的返回值),在这种情况下进行显式移动操作,会导致代码被漫无目标地的复杂化。相反,编写带返回值的简短函数,这样无论是函数的返回值还是调用侧的接受动作都可以很自然地被优化。

In general, following the guidelines in this document (including not making variables' scopes needlessly large, writing short functions that return values, returning local variables) help eliminate most need for explicit std::move.

通常情况下,遵循本文档中的准则(包括不要不必要地扩大变量作用域,编写带返回值的简短函数,返回局部变量等)可以帮助消除显式执行std::move的大部分需求。

Explicit move is needed to explicitly move an object to another scope, notably to pass it to a "sink" function and in the implementations of the move operations themselves (move constructor, move assignment operator) and swap operations.

在显式移动一个对象到另外的作用域时,显式移动是有必要的。特别是:

1.将对象传递给一个“下沉”函数时(接管变量所有权的函数,译者注)

2.实现对象自身移动操作(移动构造函数,移动赋值运算符)和交换操作时

Example, bad(反面示例)

void sink(X&& x);   // sink takes ownership of xvoid user(){    X x;    // error: cannot bind an lvalue to a rvalue reference    sink(x);    // OK: sink takes the contents of x, x must now be assumed to be empty    sink(std::move(x));    // ...    // probably a mistake    use(x);}

Usually, a std::move() is used as an argument to a && parameter. And after you do that, assume the object has been moved from (see C.64) and don't read its state again until you first set it to a new value.

通常情况下,std::move()作为为&&参数提供实参。而且在移动之后,应该认为对象已经被移走(参见C.64)并且在赋予新值之前不要获取对象的状态。

void f() {    string s1 = "supercalifragilisticexpialidocious";    string s2 = s1;             // ok, takes a copy    assert(s1 == "supercalifragilisticexpialidocious");  // ok    // bad, if you want to keep using s1's value    string s3 = move(s1);    // bad, assert will likely fail, s1 likely changed    assert(s1 == "supercalifragilisticexpialidocious");}

Example(示例)

void sink(unique_ptr p);  // pass ownership of p to sink()void f() {    auto w = make_unique();    // ...    sink(std::move(w));               // ok, give to sink()    // ...    sink(w);    // Error: unique_ptr is carefully designed so that you cannot copy it}

Notes(注意)

std::move() is a cast to && in disguise; it doesn't itself move anything, but marks a named object as a candidate that can be moved from. The language already knows the common cases where objects can be moved from, especially when returning values from functions, so don't complicate code with redundant std::move()'s.

std::move()实际上是目标为&&的类型转换;它自己不会移动任何东西,而是将命名对象标记为一个移出操作的候选者。语言已经知道对象可以被移出的一般情况,特别是函数的返回值,因此不要因为多余的std::move导致代码复杂化。

Never write std::move() just because you've heard "it's more efficient." In general, don't believe claims of "efficiency" without data (???). In general, don't complicate your code without reason (??). Never write std::move() on a const object, it is silently transformed into a copy (see Item 23 in Meyers15)

永远不要只是因为听说它更高效就使用std::move。通常不要相信那些脱离具体数据的所谓“高效”。通常不要没有理由地让代码复杂化。永远不要对常量对象调用std::move(),这会不知不觉地产生一个拷贝。

Example, bad(反面示例)

vector make_vector() {    vector result;    // ... load result with data    return std::move(result);       // bad; just write "return result;"}

Never write return move(local_variable);, because the language already knows the variable is a move candidate. Writing move in this code won't help, and can actually be detrimental because on some compilers it interferes with RVO (the return value optimization) by creating an additional reference alias to the local variable.

永远不要返回局部变量的移动结果;因为语言已经知道这个变量可以作为移动操作的候选,在这种代码中增加move代码不但没有任何帮助,而且对于某些编译器,由于产生了额外的指向局部变量的引用,增加move代码会影响RVO(返回值优化)的正常执行。

Example, bad(反面示例)

vector v = std::move(make_vector());   // bad; the std::move is entirely redundant

Never write move on a returned value such as x = move(f()); where f returns by value. The language already knows that a returned value is a temporary object that can be moved from.

如果函数f以传值方式返回结果,永远不要对这个返回值调用move操作,例如X=move(f());语言已经知道返回值是临时变量并且可以进行移出操作。

Example(示例)

void mover(X&& x) {    call_something(std::move(x));         // ok    call_something(std::forward(x));   // bad, don't std::forward an rvalue reference    call_something(x);                    // suspicious, why not std::move?}templatevoid forwarder(T&& t) {    call_something(std::move(t));         // bad, don't std::move a forwarding reference    call_something(std::forward(t));   // ok    call_something(t);                    // suspicious, why not std::forward?}

Enforcement(实施建议)

  • Flag use of std::move(x) where x is an rvalue or the language will already treat it as an rvalue, including return std::move(local_variable); and std::move(f()) on a function that returns by value.
  • 标记针对右值或者已经被语言看作是右值的对象调用std::move的情况。包括std::move(local_variable);,std::move(f()),这里函数f是一个以传值方式返回结果的函数。
  • Flag functions taking an S&& parameter if there is no const S& overload to take care of lvalues.
  • 标记没有用于处理左值的const S&型重载函数,只有一个处理右值(参数类型:S&&)的函数的情况。
  • Flag a std::moves argument passed to a parameter, except when the parameter type is an X&& rvalue reference or the type is move-only and the parameter is passed by value.
  • 标记向参数传递std::move执行结果的情况,除非参数类型是右值引用类型X&&,或者参数类型为只移动不拷贝类型并且以传值方式传递。
  • Flag when std::move is applied to a forwarding reference (T&& where T is a template parameter type). Use std::forward instead.
  • 标记对转交引用类型调用std::move的情况(T&&,这里T是模板参数)。
  • Flag when std::move is applied to other than an rvalue reference to non-const. (More general case of the previous rule to cover the non-forwarding cases.)
  • 标记std::move运用于指向非常变量的右值引用以外的情况。(前面规则的更普遍形式,以包含非转交参数的情况)
  • Flag when std::forward is applied to an rvalue reference (X&& where X is a concrete type). Use std::move instead.
  • 标记std::forward用于右值引用的情况(X&&,这里X是具体类型),转而使用std::move。
  • Flag when std::forward is applied to other than a forwarding reference. (More general case of the previous rule to cover the non-moving cases.)
  • 标记std::forward用于转交引用之外的情况。(前面规则的更普遍形式,它可以覆盖非移动参数的情况。)
  • Flag when an object is potentially moved from and the next operation is a const operation; there should first be an intervening non-const operation, ideally assignment, to first reset the object's value.
  • 标记对象可能被执行移出操作而且下一个是常量操作(读取对象值,译者注)的情况;哪里应该首先有一个非常量操作(以便修改对象值,译者注),最好是重新设置对象值的赋值操作。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es56-write-stdmove-only-when-you-need-to-explicitly-move-an-object-to-another-scope


觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

41a41c380930e25ba5074a1a56b54a05.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值