初始化时没有默认构造函数的分配

时间:2016-09-27 20:08:53

标签: c++ initialization

在这个程序中,我完全理解为什么main函数的第一部分失败并且需要被注释 - 在我在TestingClass中实现了值ctor之后,没有隐式的默认ctor。完全符合逻辑。但是,我有点惊讶地发现第二部分(test2对象的创建)成功,至少使用gcc 4.8.4。

#include <iostream>
using namespace std;

class TestingClass
{
  public:
    TestingClass(int inVal)
    {
      val = inVal;
    }

    int val;
};

TestingClass testingCreator()
{
  return TestingClass(100);
}

int main()
{
  /*
  TestingClass test1;
  test1 = testingCreator();
  cout << "Test1: " << test1.val << endl;
  */

  TestingClass test2 = testingCreator();
  cout << "Test2: " << test2.val << endl;
}

考虑它,它也是有道理的,因为对象test2在没有被构造/初始化的情况下永远不会存在,但是大多数人认为初始化就像在一条线上作为声明和赋值一样。显然,初始化比这更特殊,因为这段代码有效。

这是标准的C ++吗?它是否可以在编译器之间工作?我对以这种方式初始化不仅仅是声明(使用默认的ctor)然后分配(通过在全局函数中创建的临时对象)感兴趣。

更新:添加了副本ctor和第三个明确使用副本ctor的案例。

#include <iostream>
using namespace std;

class TestingClass
{
  public:
    TestingClass(const TestingClass &rhs)
    {
      cout << "In copy ctor" << endl;
      this->val = rhs.val + 100;
    }
    TestingClass(int inVal)
    {
      val = inVal;
    }

    int val;
};

TestingClass testingCreator()
{
  return TestingClass(100);
}

int main()
{
  /*
  TestingClass test1;
  test1 = testingCreator();
  cout << "Test1: " << test1.val << endl;
  */

  TestingClass test2 = testingCreator();
  cout << "Test2: " << test2.val << endl;

  TestingClass test3(test2);
  cout << "Test3: " << test3.val << endl;
}

输出:

Test2: 100
In copy ctor
Test3: 200

2 个答案:

答案 0 :(得分:2)

你对TestingClass test2 = testingCreator();所做的事情的思考是有缺陷的。当你看到

type name = stuff;

您不创建name,然后为其分配stuff。您要做的是从name复制初始化stuff。这意味着您可以调用复制或移动构造函数。一般来说,这个调用可以通过优化编译器来省略,但如果不是,那就是你会看到的。在任何一种情况下,都不会调用默认构造函数。

在你的第一个例子中

TestingClass test1;

强制调用默认构造函数,因为没有构造函数会导致错误。

答案 1 :(得分:0)

test2TestingClass的复制构造函数定义,将testingCreator的结果作为参数。复制构造函数TestingClass::TestingClass(const TestingClass&)由编译器自动生成,C ++标准保证它复制val字段。