gpt4 book ai didi

c++11 - 移动构造函数不适用于成员变量?

转载 作者:行者123 更新时间:2023-12-02 23:28:55 29 4
gpt4 key购买 nike

为什么这个:(vs2010) 没有在类中移动向量?

#include <vector>

class MoveTest
{
public:
std::vector<int> m_things;
};

int _tmain(int argc, _TCHAR* argv[])
{
MoveTest m;
m.m_things.push_back(12);

MoveTest m2 = std::move(m);
// std::vector has been copied, not moved

return 0;
}

这是否意味着每个使用 std::vector 的类(和其他可移动类)都应该有一个显式的移动构造函数和赋值?

最佳答案

除了已经给出的关于这些规则相对于 vs2010 发布时的延迟的良好答案之外,

隐式生成的移动构造函数的规则是:

If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if

  • X does not have a user-declared copy constructor,
  • X does not have a user-declared copy assignment operator,
  • X does not have a user-declared move assignment operator,
  • X does not have a user-declared destructor, and
  • the move constructor would not be implicitly defined as deleted.

隐式生成的移动赋值运算符的规则遵循上述模式。

隐式生成复制构造函数的规则已略有更改!

If the class definition does not explicitly declare a copy constructor, one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted (8.4). The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor.

对于复制赋值运算符也类似:

If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy assignment operator is defined as deleted; otherwise, it is defined as defaulted (8.4). The latter case is deprecated if the class has a user-declared copy constructor or a user-declared destructor.

底线:3 条规则现在是 5 条规则。您可以忽略所有 5 条规则(如果默认行为适合您),或者您需要考虑(并可能定义)所有 5 条规则:

  1. 复制构造函数
  2. 复制作业
  3. 移动构造函数
  4. 移 Action 业
  5. 析构函数

关于c++11 - 移动构造函数不适用于成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5976220/

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