C++ Object Instantiation vs Assignment

后端 未结 4 746
心在旅途
心在旅途 2020-12-05 08:47

What is the difference between this:

TestClass t;

And this:

TestClass t = TestClass();

I expected that th

相关标签:
4条回答
  • 2020-12-05 09:05

    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.

    0 讨论(0)
  • 2020-12-05 09:07

    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.

    0 讨论(0)
  • 2020-12-05 09:27

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

    0 讨论(0)
  • 2020-12-05 09: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;
    
    0 讨论(0)
提交回复
热议问题