C++ Object Instantiation vs Assignment

混江龙づ霸主 提交于 2019-11-27 19:52:29
TestClass t;

calls the default constructor.

TestClass t = TestClass();

is a copy initialization. It will call the default constructor for TestClass() and then the copy constructor (theoretically, copying is subject to copy elision). No assignment takes place here.

There's also the notion of direct initialization:

TestClass t(TestClass());

If you want to use the assignment operator:

TestClass t;
TestClass s;
t = s;
Flexo

The first case is quite simple - constructs an instance using the default constructor.

The second class is Constructing an anonymous object and then calling the copy constructor. Notice that here the = is not assignment, it's similar to (but not identical) writing:

TestClass t(TestClass());

We can verify that this needs the copy constructor to be available by making it unavailable, e.g.:

#include <iostream>

struct TestClass {
  TestClass() { std::cout << "Ctor" << std::endl; }
  TestClass(const TestClass&)  = delete;
};

int main() {
  TestClass t = TestClass();
}

Which fails to compile because of the deleted copy constructor. (In C++03 you can use private: instead).

What's actually happening most likely though is that your compiler is doing Return value optimisation, whereby it's allowed to ommit the call to the copy constructor entirely provided a suitable one exists and would be accessible.

In the first one, you are calling the default constructor implicitly. And in the second one you're calling it explicitly.

The latter one could call copy constructor and thus requires one to be public.

Edit: I certainly drew far too big conclusions from the type name you used. The sentence above only applies for class-types (i.e. not POD). For POD types, the former leaves the variable uninitialized, while the latter initializes it with so-called "default" value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!