"Defaulted"移动构造函数和赋值 - 奇怪的行为

"Defaulted" move constructor and assignment - weird behaviour

本文关键字:赋值 Defaulted 移动 构造函数      更新时间:2023-10-16

所以我有一个简单的类示例,它有两个成员变量。我已经声明了一个副本和一个移动构造函数,它们是= 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>),则移动的矢量最终将有效地为空。