gpt4 book ai didi

c++ - "Defaulted" move 构造函数和赋值 - 奇怪的行为

转载 作者:行者123 更新时间:2023-11-30 01:12:34 24 4
gpt4 key购买 nike

所以我有一个类的简单示例,它有两个成员变量。我已经声明了一个拷贝和一个 move 构造函数,它们是 = default,这将强制编译器为我生成它们。现在我的问题是这个。使用 move 构造函数(或赋值)时,为什么我 move 的对象保持不变?

例如,如果我有:

myclass obj(4, 5);
myclass obj2 = std::move(4, 5);

据我了解,在第二行之后 obj 将包含“无”,因为它将被 move 到 obj2 中,它将具有值 ( 4、5)。我知道我不是用来纠正这里的术语....

完整代码:

#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 的默认 move 只是一个拷贝。

关于c++ - "Defaulted" move 构造函数和赋值 - 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33919931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com