鉴于我对返回值优化的理解,我对为什么在下面的示例代码中调用移动构造函数感到困惑:
#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 编译器。