c ++ 11的举动没有生效吗? [英] c++11 move not take effective?

查看:92
本文介绍了c ++ 11的举动没有生效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我测试了c ++ 11 move函数,但是没有生效.谁能告诉我为什么?谢谢.代码如下:

I tested c++11 move function, but not become effective. Who can tell me why ? Thanks. The code is as follows:

class Base {
  public:
   Base() { cout << "Base" << endl;}
   ~Base() { cout << "~Base" << endl;}

   Base(const Base& base) { cout << "Copy" << endl; }
   Base& operator=(const Base& base) {cout << "operator=" << endl;}

   Base(Base&& base) { cout << "move" << endl;}
   Base& operator=(Base&& base) { cout << "move=" << endl;}
};

Base b;

Base&& GetResult() {
  return std::move(b);
} 

int main() {
Base&& tmp = GetResult();

cout << &b << endl;
cout << &tmp << endl;

}

输出:

 Base
 0x6013a0
 0x6013a0
 ~Base

为什么不调用move copymove operator=?为什么地址相同?

Why move copy and move operator= not be called ? And why address is the same ?

推荐答案

要添加到现有的出色答案中,我相信这里的主要困惑是std::move的作用.

To add to the excellent existing answers, I believe the main point of confusion here is what std::move does.

std::move不会移动.

std::move does not move.

它是 abysmally 的名字.

它只为您提供一个xvalue,该xvalue指向您所提供的任何内容;此xvalue将绑定到右值引用,而左值则不会.这意味着可以将std::move 的结果提供给move构造函数或move赋值运算符.但是,它不会为您做到这一点,您在这里也不会这样做.

It only gives you an xvalue referring to whatever you gave it; this xvalue will bind to a rvalue reference where an lvalue won't. This means the result of std::move can be given to a move constructor or move assignment operator. However, it does not do that for you, and you do not do it here.

鉴于对命名的强烈批评,您肯定有其他建议
user2079303

Given such strong criticism for the naming, surely you have an alternative suggestion
– user2079303

这是一个很容易理解的话题,但是 C ++的创建者建议std::rval

This is a well-trodden topic, but the creator of C++ suggests std::rval, and one of the architects of modern C++ suggests std::rvalue_cast (even though you actually get an xvalue).

我个人认为std::moveable应该是一个很好的中间立场.

Personally, I think std::moveable would have been a nice middle ground.

这篇关于c ++ 11的举动没有生效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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