c++ - 什么构造函数被调用,它不是移动

标签 c++ c++11

我创建了一个基本测试类来了解移动构造函数的工作原理。移动构造函数似乎没有被调用,我不确定实际调用的是什么构造函数。如果我使用 std::move 然后调用移动构造函数,但常规 R 值实际上不会调用它。为什么会这样,实际上调用的是什么构造函数?我正在使用 g++ 4.6.3

#include <iostream>
#include <cstring>

class Test
{
  int a;
  int b;
  int* c;

public:
  Test(int one, int two)
  {
    std::cout << "Param Constructor" << "\n";
    a = one;
    b = two;
  }

  Test()
  {
    std::cout << "Default Constructor" << "\n";
    a = 1;
    b = 2;
  }

  ~Test()
  {
    std::cout << "Deconstructor" << "\n";
  }

  Test(const Test& test)
  {
    a = test.a;
    b = test.b;
    std::cout << "Copy constructor called" << "\n";
  }

  Test(Test&& test)
  {
    std::cout << "Move constructor called" << "\n";
    a = test.a;
    b = test.b;
  }

  Test& operator=(const Test& test)
  {
    std::cout << "in operator=" << "\n";
    a = test.a;
    b = test.b;
    return *this;
  }
};

Test createTest()
{
  return Test(1,2);
}

int main()
{
  Test test(createTest());
  Test test2 = test;
  std::cout << "After logic" << "\n";
  return 0;
}

我得到的输出:

Param Constructor
Copy constructor called
After logic
Deconstructor
Deconstructor

我创建了一个名为 test 的 Test 类型的对象,但是没有创建它的输出?我期待这个输出:

Param Constructor
Move Constructor // (Missing)
Deconstructor //Deleting instance from createTest (Missing)
Copy constructor called
After logic
Deconstructor
Deconstructor

最佳答案

what constructor is actually being called?

根本没有构造函数。计算析构函数调用的次数。你会发现比你想象的少了一个。您期望构建的临时对象根本没有创建。

Why is this happening

编译器避免创建临时文件。取而代之的是,该对象是在它本来会被移动到的地方 build 的。这称为复制省略。

关于c++ - 什么构造函数被调用,它不是移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41496913/

相关文章:

c++ - 为什么我们不能在 C++ 中转发声明具有已知大小的类/结构?

c++ - 使用 mouseMoveEvent 限制 QGraphicsItem 的移动

eclipse - Eclipse CDT无法解析的原子类型

c++11 - CUDA 8.0 : Compile Error with Template Friend in Namespace

c++ - 具有不同签名的 std::function vector

c++ - 交换中没有竞争条件吗?

c++ - 调用模板函数的误报错误 503

c++不合逻辑> =处理vector.size()时的比较很可能是由于size_type未签名

c++ - 什么是复制省略和返回值优化?

c++ - Boost Multi-Index 中的多索引查询