std :: move的逆是否存在? [英] Does the inverse of std::move exist?

查看:120
本文介绍了std :: move的逆是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: move 可以用来显式地允许移动语义,当移动不会被隐式允许时(例如

现在,我想知道( esp 。在局部返回和隐式移动的上下文中),如果有这样的事情作为 std :: move 的逆,将

std :: move 将一个左值转换为右值,它本质上由 static_cast 。最接近我可以想到的相反的是这两个类型转换:

  static_cast< T& * rvalue-expression * /)
static_cast< const T&>(/ * rvalue-expression * /)


b $ b

这样的例子如下:

  #include< iostream> 

void f(const int&)
{std :: cout< const-lval-ref< std :: endl; }

void f(int&&)
{std :: cout< rval-ref< std :: endl; }

int main()
{
f(static_cast< const int&>(3)
return 0;
}

投放prvalue 3 const int& 确保选择 f 的lvalue-overload。



在大多数情况下,只需赋值给变量,就可以自动进行这个右值修改:

  int a = 3; 

在此行后面使用 a 它将是一个左值。即使 a 被声明为右值引用,也是如此:

  int && a = 3; 

在这里, a (基本上因为它有一个名字)。



我可以想象一个显式的演员有任何相关的效果的唯一情况是我上面的第一个例子。在那里,当处理诸如 3 的prvalues或通过拷贝从函数调用返回的临时值时,唯一的合法转换是const-reference(不允许非const引用绑定到prvalue)。


std::move can be used to explicitly allow move semantics when the move wouldn't be already allowed implicitly (such as often when returning a local object from a function).

Now, I was wondering (esp. in the context of local return and implicit move there), if there is such a thing as the inverse of std::movethat will prevent moving the object (but still allow copying).

Does this even make sense?

解决方案

std::move converts an lvalue into an rvalue, and it does this essentially by static_cast. The closest to what I can think of as the opposite are these two type casts:

static_cast<T &>(/*rvalue-expression*/)
static_cast<const T&>(/*rvalue-expression*/)

An example of this can be seen below:

#include <iostream>

void f(const int &)
{ std::cout << "const-lval-ref" << std::endl; }

void f(int &&)
{ std::cout << "rval-ref" << std::endl; }

int main()
{
  f(static_cast<const int &>(3));
  return 0;
}

Casting the prvalue 3 to const int & ensures that the lvalue-overload of f is chosen.

In most contexts, you get this rvalue-to-lvalue modification automatically, simply by assigning to a variable:

int a = 3;

When you use a after this line, it will be an lvalue. This is true even when a is declared as rvalue reference:

int &&a = 3;

Here, too, a becomes an lvalue (basically because it "has a name").

The only situation where I can imagine an explicit cast to have any relevant effect is my first example above. And there, when dealing with prvalues like 3 or temporaries returned from function calls by copy, the only legal cast is to const-reference (a non-const-reference is not allowed to bind to a prvalue).

这篇关于std :: move的逆是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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