【发布时间】: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