【发布时间】:2018-06-25 05:58:35
【问题描述】:
在 C++11 中,如果复制和移动赋值都可用,编译器会在参数是左值时自动选择复制赋值,如果是右值则自动选择移动赋值。使用std::move 可以显式选择左值的移动分配。但是怎么可能显式地选择右值的复制赋值呢?
代码示例:
#include <iostream>
class testClass
{
public:
testClass &operator=(const int &other) {
std::cout << "Copy assignment chosen." << std::endl;
return *this;
}
testClass &operator=(int &&other) {
std::cout << "Move assignment chosen." << std::endl;
return *this;
}
};
int main(int argc, char *argv[])
{
int a = 4;
testClass test;
test = a; // Selects copy assignment
test = 3; // Selects move assignment
test = std::move(a); // Selects move assignment
// test = std::copy(3); // <--- This does not work
return 0;
}
【问题讨论】:
-
您可以将
static_cast转为const int&:test = static_cast<const int&>(3); -
@rahnema1 评论不是用来回答的,你知道...
-
@NickyC :有时只想写一句话,而一句话很少是一个好的答案。 ;-]
-
如果您同时拥有这两个运算符,则编写该功能以正确处理参数。出于这个原因,“手动”选择不同的运算符作为“自然正确”的运算符看起来不是很有用。与 std::move 一样,它会导致对象“无效状态”。如果这是预期的,很好!但是如果将右值作为左值处理呢?
-
我很好奇这样做的动机