gpt4 book ai didi

c++ - 为什么 C++11 move 运算符 (=) 的行为不同

转载 作者:太空狗 更新时间:2023-10-29 23:25:23 27 4
gpt4 key购买 nike

我已经在 C++11 中测试了 move Semantic。我写了一个带有 move 构造函数的类。

class DefaultConstructor
{
public:
DefaultConstructor(std::vector<int> test) :
m_vec(std::forward<std::vector<int>>(test))
{

};

DefaultConstructor(DefaultConstructor &&def) :
m_vec(std::forward<std::vector<int>>(def.m_vec))
{
}

DefaultConstructor& operator=(DefaultConstructor&& def) {
m_vec = std::move(def.m_vec);
return *this;
}

DefaultConstructor& operator=(const DefaultConstructor&) = delete;
DefaultConstructor(DefaultConstructor &) = delete;

std::vector<int> m_vec;
};

我写了一个使用 move 语义的主函数。我了解 move 语义中发生的事情,它是一个很棒的工具。但是有些行为对我来说无法解释。当我调用主函数 DefaultConstructor testConstructor2 = std::move(testConstructor); 时,应该调用 DefaultConstructor& operator=(DefaultConstructor&& def)。但是 Visual Studio 2015 调用 move 构造函数。

int main()
{
std::vector<int> test = { 1, 2, 3, 4, 5 };
DefaultConstructor testConstructor(std::move(test));

DefaultConstructor testConstructor2 = std::move(testConstructor);
DefaultConstructor &testConstructor3 = DefaultConstructor({ 6, 7, 8, 9 });
DefaultConstructor testConstructor4 = std::move(testConstructor3);
swapMove(testConstructor, testConstructor2);
}

好吧,我想也许 = move 运算符不再需要了。但是我尝试了 SwapMove 函数。此函数调用 = move 运算符。

template<typename T>
void swapMove(T &a, T &b)
{
T tmp(std::move(a));
a = std::move(b);
b = std::move(tmp);
}

有人能解释一下这两个调用之间到底有什么区别吗?调用 a = std::move(b);DefaultConstructor testConstructor2 = std::move(testConstructor); 不应该有相同的行为吗?

最佳答案

语法

 DefaultConstructor testConstructor2 = something;

总是调用构造函数,因为对象 testConstructor2 尚不存在。 operator= 只能在已经构造的对象的上下文中调用。

关于c++ - 为什么 C++11 move 运算符 (=) 的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32319602/

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