"Defaulted"移动构造函数和赋值 - 奇怪的行为
"Defaulted" move constructor and assignment - weird behaviour
所以我有一个简单的类示例,它有两个成员变量。我已经声明了一个副本和一个移动构造函数,它们是= default
,这将迫使编译器为我生成它们。当使用移动构造函数(或赋值)时,为什么我移动的对象保持不变?
例如,如果我有:
myclass obj(4, 5);
myclass obj2 = std::move(4, 5);
据我所知,在第二行之后,obj
将包含"nothing",因为它将被移动到值为(4, 5)
的obj2
中。我知道我不习惯纠正这里的术语。。。。
完整代码:
#include <iostream>
#include <utility>
template<class T1, class T2>
class Pair
{
public:
T1 first;
T2 second;
public:
//CONSTRUCTORS
constexpr Pair() = default;
constexpr Pair(const T1& _first, const T2& _second)
: first(_first), second(_second)
{}
constexpr Pair(T1&& _first, T2&& _second)
: first(std::forward<T1>(_first)), second(std::forward<T2>(_second))
{}
constexpr Pair(const Pair&) = default;
constexpr Pair(Pair&&) = default;
//ASSIGNMENT
Pair &operator=(const Pair&) = default;
Pair &operator=(Pair&&) = default;
};
int main()
{
Pair<int, int> p(1, 2);
Pair<int, int> p2 = p; //all good, p = {1, 2} and p2 = {1, 2}
Pair<int, int> p3 = std::move(p); //p = {1, 2} and p3 = {1, 2}
//why isn't p "moved" into p3??
//p should be empty??
//same thing occurs with the move assignment. why?
std::cout << p.first << " " << p.second << "n";
std::cout << p2.first << " " << p2.second << "n";
std::cout << p3.first << " " << p3.second << "n";
}
现场示例:http://coliru.stacked-crooked.com/a/82d85da23eb44e66
int
的默认移动只是一个副本。
默认的移动构造函数和移动赋值只会对所有成员调用std::move
。就像副本一样,默认的副本构造函数简单地调用所有成员的副本。
您的代码是正确的,在调用std::move
之后,移动的数据仍然存在是正常的。为什么?因为基元上的std::move
会复制它们。编译器不会生成将int移动到0
的代码,所以它是一个简单的副本。但是,如果配对包含更复杂的类型(如std::vector<int>
),则移动的矢量最终将有效地为空。
相关文章:
- 为"adjacent"变量赋值时出现问题
- C++中的赋值发生,尽管右侧出现异常
- 用C++中的sscanf赋值
- 为std::string的某个索引赋值
- 重载Singly Linked List中的赋值运算符
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- gtest_使用setargpointee在函数中赋值
- 非常量变量只读位置的赋值
- 使用赋值运算符重载从类中返回jobject
- C++数据文件、数组和计算赋值
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 全局作用域中函数指针的赋值
- 错误:在为指针赋值时,void值没有被忽略
- 标准库类型的赋值运算符的引用限定符
- 关于 c++ 函数中指针赋值的简单问题
- 复制构造函数、赋值运算符C++
- 标准::变体的赋值运算符
- cin >> int 给定一个字符串将 int 赋值为 0
- if 子句中的赋值不起作用
- "Defaulted"移动构造函数和赋值 - 奇怪的行为