【问题标题】:Why is the move constructor being called?为什么调用移动构造函数?
【发布时间】:2023-03-18 06:25:02
【问题描述】:

鉴于我对返回值优化的理解,我对为什么在下面的示例代码中调用移动构造函数感到困惑:

#include <vector>
#include <iostream>

class MyCustomType
{
public:
  MyCustomType()
  {
    std::cout << "Constructor called" << std::endl;
  }

  MyCustomType(const MyCustomType & inOther) : // copy constructor
    mData(inOther.mData)
  {
    std::cout << "Copy constructor called" << std::endl;
  }

  MyCustomType(MyCustomType && inOther) : // move constructor
    mData(std::move(inOther.mData))
  {
    std::cout << "Move constructor called" << std::endl;
  }

private:
  std::vector<int> mData;
};

MyCustomType getCustomType()
{
  MyCustomType _customType;
  return _customType;
}

int main()
{
  MyCustomType _t = getCustomType();
}

输出:

Constructor called
Move constructor called

我假设只有一个 MyCustomType 实例被构造并直接分配给_t。

关于信息,我使用的是 VC14 编译器。

【问题讨论】:

  • 你为什么这么认为?是因为 C++ 规则(您会误解)还是因为优化(可能有点不可预测)?
  • @BoBTFish 两者,我假设 C++ 标准在这种情况下允许单一构造,并希望编译器足够聪明地注意到它。
  • 如果你只想要一个没有任何其他构造函数调用的实例,它会是 MyCustomType _t(); 但在你的帖子中首先创建一个临时实例 getCustomType() 并且赋值运算符不会启动复制构造而是一个移动建设。从而节省资源。 C++ 并没有简化你的代码,它会转换这两个语句。
  • 另见stackoverflow.com/questions/17473753/…。如果你在发布模式下编译,MSVC 也可能会消除这一举动。另请注意,移动构造函数通常应采用非常量参数
  • @Aeonos:你的意思是MyCustomType _t{};(因为你有麻烦的解析:函数声明)。

标签: c++ c++11 move-constructor rvo


【解决方案1】:

在您的示例中,您假设将应用 NRVO。但是NRVO只是一个优化,不保证编译器会用到^.

我已经使用http://webcompiler.cloudapp.net/ 测试了您的示例。

默认的编译器选项有:

/EHsc /nologo /W4

在这种情况下,输出与您的相似:

Constructor called

Move constructor called

但如果启用了适当的优化,例如 /O2 标志:

/O2 /EHsc /nologo /W4

那么输出是:

Constructor called

^ 正如@einpoklum 在 cmets 中提到的,自 C++17 以来规则发生了变化。

【讨论】:

  • 实际上,在 C++17 中,我认为在合理的条件下,返回值的复制省略将是 guaranteed。
  • @einpoklum 好话!无论如何,OP使用VC14编译器:)
  • @einpoklum 只有在返回prvalue时才保证;至少不是 OP 的情况。
  • @songyuanyao:很公平,但是这个答案说 NRVO 只是一种优化,所以我必须对其进行限定。
  • @einpoklum 是的。更准确地说,OP 的 NRVO 只是一种优化。
【解决方案2】:

因为表达式 getCustomType() 是 prvalue(rvalue),并且参数可以比参数更具有 cv 限定。

为了看到“更多”的复制省略,您可以尝试发布编译模式。

顺便说一句,inOther.mData 没有被移动,mData(std::move(inOther.mData)) 实际上会调用向量的复制构造函数。

【讨论】:

  • 谢谢,将移动构造函数修改为非常量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-10
  • 1970-01-01
  • 1970-01-01
  • 2014-01-24
相关资源
最近更新 更多