我有以下代码:
#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&&)
叫?什么时候调用复制构造函数?
最佳答案
问题在于 a
AddData()
中的参数:
void AddData(const A&& a) // <-- const reference!!!
{
aList.push_back(std::move(a)); // selects push_back(const A&)
}
a
上面的参数是 const
右值引用。您正在使用 std::move()
进行标记一个 const
目的。标记
const
带有 std::move()
的对象对于 move 语义而言, move 没有任何影响,因为您不能从 const
move 。对象(即,您需要更改移出对象,但它是 const
-qualified)。右值引用不绑定(bind)到
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&&)
}
关于c++ - 为什么调用复制构造函数而不是 move 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62634487/