在C++ 11中,如果复制和移动赋值都可用,则编译器会在参数为左值时自动选择复制赋值,如果是左值则移动赋值.使用std::move它可以明确地选择左值的移动分配.但是如何明确选择rvalue的复制赋值呢?
代码示例:
#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;
}
Run Code Online (Sandbox Code Playgroud)
小智 19
一种可能的方法是编写自己copy的对象以将对象绑定到左值引用:
template <class T>
constexpr T& copy(T&& t) noexcept
{
return t;
}
Run Code Online (Sandbox Code Playgroud)
你可以这样测试它:
test = copy(a);
test = copy(3);
test = copy(std::move(a));
Run Code Online (Sandbox Code Playgroud)
您可以将此函数放在自己的命名空间中以保持清洁.您也可以为它选择一个更好的名称.
为了解决生命问题的恐惧,这里有一些注意事项:
copy函数接受引用并立即返回相同的引用.这意味着调用者负责控制生命周期.=.你可以static_cast到const int&:
test = static_cast<const int&>(3);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1501 次 |
| 最近记录: |