C++ Object Instantiation vs Assignment

后端 未结 4 759
心在旅途
心在旅途 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: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;
    

提交回复
热议问题