c++ 移动语义 move

One of the most important concepts introduced in C++11 was move semanticsMove semantics is a way to avoid expensive deep copy operations and replace them with cheaper move operations. Essentially, you can think of it as turning a deep copy into a shallow copy.

Move semantics came along with several more or less related features, such as rvalue referencesxvaluesforwarding  referencesperfect forwarding, and so on. The standard C++ library gained a function template called std::move, which, despite its name, does not move anything. std::move merely casts its argument to an rvalue reference to allow moving it, but doesn't guarantee a move operation. For example, we can write a more effective version of swap using std::move:

template<typename T>
void swap(T& a, T& b)
{
  T t(std::move (a));
  a = std::move (b);
  b = std::move (t);
}

This version of swap consists of one move construction and two move assignments and does not involve any deep copies. All is well. However, std::move must be used judiciously; using it blithely may lead to performance degradation, or simply be redundant, affecting readability of the code. Fortunately, the compiler can sometimes help with finding such wrong uses of std::move. In this article, I will introduce two new warnings I've implemented for GCC 9 that deal with incorrect usage of std::move.

-Wpessimizing-move

When returning a local variable of the same class type as the function return type, the compiler is free to omit any copying or moving (i.e., perform copy/move elision), if the variable we are returning is a non-volatile automatic object and is not a function parameter. In such a case, the compiler can construct the object directly in its final destination (i.e., in the caller's stack frame). The compiler is free to perform this optimization even when the move/copy construction has side effects. Additionally, C++17 says that copy elision is mandatory in certain situations. This is what we call Named Return Value Optimization (NRVO). (Note that this optimization does not depend on any of the -O levels.) For instance:

struct T {
  // ...
};

T fn()
{
  T t;
  return t;
}

T t = fn ();

The object a function returns doesn't need to have a name. For example, the return statement in the function fn above might be return T(); and copy elision would still apply. In this case, this optimization is simply Return Value Optimization (RVO).

Some programmers might be tempted to "optimize" the code by putting std::move into the return statement like this:

T fn()
{
  T t;
  return std::move (t);
}

However, here the call to std::move precludes the NRVO, because it breaks the conditions specified in the C++ standard, namely [class.copy.elision]: the returned expression must be a name. The reason for this is that std::move returns a reference, and in general, the compiler can't know to what object the function returns a reference to. So GCC 9 will issue a warning (when -Wall is in effect):

t.C:8:20: warning: moving a local object in a return statement prevents copy elision [-Wpessimizing-move]
8 | return std::move (t);
  |        ~~~~~~~~~~^~~
t.C:8:20: note: remove ‘std::move’ call

-Wredundant-move

When the class object that a function returns is a function parameter, copy elision is not possible. However, when all the other conditions for the RVO are satisfied, C++ (as per the resolution of Core Issue 1148) says that a move operation should be used: overload resolution is performed as if the object were an rvalue (this is known as two-stage overload resolution). The parameter is an lvalue (because it has a name), but it's about to be destroyed. Thus, the compiler ought to treat is as an rvalue.

For instance:

struct T {
  T(const T&) = delete;
  T(T&&);
};

T fn(T t)
{
  return t; // move used implicitly
}

Explicitly using return std::move (t); here would not be pessimizing—a move would be used in any case—it is merely redundant. The compiler can now point that out using the new warning -Wredundant-move, enabled by -Wextra:

r.C:8:21: warning: redundant move in return statement [-Wredundant-move]
8 | return std::move(t); // move used implicitly
  |        ~~~~~~~~~^~~
r.C:8:21: note: remove ‘std::move’ call

Because the GNU C++ compiler implements Core Issue 1579, the following call to std::move is also redundant:

struct U { };
struct T { operator U(); };

U f()
{
  T t;
  return std::move (t);
}

Copy elision isn't possible here because the types T and U don't match. But, the rules for the implicit rvalue treatment are less strict than the rules for the RVO, and the call to std::move is not necessary.

There are situations where returning std::move (expr) makes sense, however. The rules for the implicit move require that the selected constructor take an rvalue reference to the returned object's type. Sometimes that isn't the case. For example, when a function returns an object whose type is a class derived from the class type the function returns. In that case, overload resolution is performed a second time, this time treating the object as an lvalue:

struct U { };
struct T : U { };

U f()
{
  T t;
  return std::move (t);
}

While in general std::move is a great addition to the language, it's not always appropriate to use it, and, sadly, the rules are fairly complicated. Fortunately, the compiler is able to recognize the contexts where a call to std::move would either prevent elision of a move or a copy—or would actually not make a difference—and warns appropriately. Therefore, we recommend enabling these warnings and perhaps adjusting the code base. The reward may be a minor performance gain and cleaner code. GCC 9 will be part of Fedora 30, but you can try it right now on Godbolt.

Last updated: April 23, 2019
posted @   Bigben  阅读(251)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示