【问题标题】:Given a rvalue, why move ctor is a better match than const copy ctor? [duplicate]给定一个右值,为什么 move ctor 比 const copy ctor 更匹配? [复制]
【发布时间】:2018-08-01 07:55:23
【问题描述】:

示例代码,C++11,-fno-elide-constructors。

#include <iostream>
#include <string>
using namespace std;

class ClassA
{
    int a, b;
public:
    ClassA() = default;
    ClassA(const ClassA &obj)
    {
        cout << "copy constructor called" << endl;
    }

    ClassA(ClassA &&obj) {
        cout << "move ctor called" << endl;
    }
};

ClassA bar(ClassA &str)
{
    return str;  //call copy ctor
}

int main()
{
    ClassA str;
    ClassA foo = bar(str); //call move ctor
    return 0;
}

https://wandbox.org/permlink/DyALfRETs2LfWSjc

为什么这个赋值 ClassA foo = bar(str); 调用 move ctor 而不是 copy ctor?由于 const 左值引用和右值引用都可以接受右值。

【问题讨论】:

  • 我不认为这是一个重复的问题!首先ClassA foo = bar(str)等价于Class foo(bar(str)); copy ctor 发生是因为您的 -fno-elide-constructors 和变量 str 不是临时对象。因此,如果您返回 std::move(str),它将改为调用 move ctor。而 move ctor 发生是因为函数 bar(str) 返回了一个临时对象。所以这不是关于“const 左值引用和右值引用都可以接受右值”。
  • @WeiGuo 是的,这是一个重复的..我从中得到了我想要的。

标签: c++


【解决方案1】:

const lvalue 引用可以绑定到任何东西,所以如果编译器倾向于这个而不是 rvalue 引用,那么 move 构造函数将不会被调用,如果 copy提供了构造函数,这将破坏同时拥有两者的目的。

接受function 的rvalue 引用是接受const lvalue 引用的更通用的版本的更专业版本,编译器始终选择最专业的版本。

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 2019-11-09
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2021-03-30
    相关资源
    最近更新 更多