c++ - move 构造函数可以接受类本身以外的参数吗?

标签 c++ visual-studio c++11 move-semantics move-constructor

基本上, move 构造函数的参数是类本身。

但是,如果我想在没有复制操作的情况下从左值构造一个类的对象,我可以这样做吗?

class A{
   A(const LargeDataType& inData):data(inData) {} // constructor 1
   A(LargeDataType&& inData):data(std::move(inData)) {} // constructor 2
   private:
        LargeDataType data;
};

使用方法:

方法一:

LargeDataType outData = 100;
A objA(std::move(outData)); // call constructor 2

方法二(如果构造函数二没有实现):

LargeDataType outData = 100;
A objA(std::move(outData)); // call constructor 1

这样在构造objA的时候就没有复制操作了。我的问题是:

  1. 这样创建 move 构造函数合法吗?

  2. 这比传统的构造函数更有效,因为在创建 objA 期间不需要复制?

  3. 方法2是否可以比方法1更好并具有相同的效率?

非常感谢!

最佳答案

您拥有的不是 move 构造函数。它只是一个将右值引用作为参数的构造函数。它们是非常好的构造函数,但它们不是 move 构造函数。

来自 C++11 标准 (12.8/3):

A non-template constructor for class X is a move constructor if its first parameter is of type X&&, const X&&, volatile X&&, or const volatile X&&, and either there are no other parameters or else all other parameters have default arguments (8.3.6).

只有

A(A&& a) { ... }
A(const A&& a) { ... }
A(volatile A&& a) { ... }
A(volatile const A&& a) { ... }

可能称为 move 构造函数。

如果除了上述之外还有带默认值的参数,它们也有资格作为 move 构造函数。例如

A(A&& a, T arg = {}) { ... }

关于c++ - move 构造函数可以接受类本身以外的参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43481206/

相关文章:

c++ - 使用 std::function 移动语义

c++ - 为什么我的程序有时只能正确识别数组中的最高值和最低值?

c++ - 一行中的最后一个数组元素和下一行中具有相同指针的第一个元素

visual-studio - 使用 Visual Studio 插件从本地和远程计算机访问 SVN

c# - 从 hexdigit 隐藏编程计算机的文件路径

c++ - 在捕获 `this->` 的 lambda 中使用 `this`

c++ - 使用 VS2012 和 DirectX 的警告(2010 年 6 月)

c++ - 安全删除 StackView 转换中使用的 QML 组件

c++ - 包含预编译 header 的错误

visual-studio - 在 Visual Studio 的监 window 口中展开所有值