为什么调用复制构造函数而不是移动构造函数?

Why is copy constructor called rather than move constructor?

本文关键字:构造函数 移动 调用 复制 为什么      更新时间:2023-10-16

我有以下代码:

#include <bits/stdc++.h>
using namespace std;
class A {
public:
A(const A& a) noexcept { cout << "copy constructor" << endl; }
A& operator=(const A& a) noexcept { cout << "copy assignment operator" << endl; }
A(A&& a) noexcept { cout << "move constructor" << endl; }
A& operator=(A&& a) noexcept { cout << "move assignment operator" << endl; }
A() { cout << "default constructor" << endl; }
};
vector<A> aList;
void AddData(const A&& a)
{
aList.push_back(std::move(a));
}
int main()
{
AddData(A());
return 0;
}

输出default constructor copy constructor。 请告诉我右值引用push_back(T&&)叫吗?什么时候调用复制构造函数?

问题出在AddData()中的a参数:

void AddData(const A&& a) // <-- const reference!!!
{
aList.push_back(std::move(a)); // selects push_back(const A&)
}

上面的a参数是const值引用。您正在用std::move()标记const对象。

在移动语义方面,使用std::move()标记const对象对移动没有影响,因为您无法从const对象移动(即,您需要更改移出对象,但它是const限定的(。

右值引用不绑定到const对象,但const左值引用绑定。因此,选择了push_back(const A&)重载而不是push_back(A&&)重载,因此将复制构造A对象。

<小时 />

解决方案

请改用非const右值引用:

void AddData(A&& a) // <-- non-const reference
{
aList.push_back(std::move(a)); // selects push_back(A&&)
}