c++ - Why in this situation only one constructor is called but two destructors are called? -


in first time,the code looks below:

#include "stdafx.h" #include<iostream> using namespace std;  class test{ public:     explicit test(int);     ~test();     //test(test&);     int varint; }; test::test(int temp){     varint = temp;     cout << "call test::constructor\n"; } test::~test(){     cout << "call test::destructor\n"; } /*test::test(test&temp){     varint = temp.varint;     cout << "call test::copy constructor\n"; }*/ void func(test temp){     cout << "call func\n"; } int _tmain(int argc, _tchar* argv[]) {     func(test(1));     return 0; } 

output:

call test::constructor call func call test::destructor call test::destructor 

this confuses me,cause there's 1 object created(as argument of func),but 2 destructors called after function ends. started wonder,is because default copy constructor called?so wrote definition of copy constructor,which made things more strange. after add commented-out code can see above,namely definition of copy constructor,into class,the output became this:

output:

call test::constructor call func call test::destructor 

things became right now. can explain phenomenon me?thank u much.

  • your interpretation of original code (that implicitly-declared copy constructor being called) correct.
    • depending on version of standard compiler implementing, may using implicitly-declared move constructor instead. amounts same thing.
  • your modified code (where you've explicitly provided copy constructor) happens triggering the copy elision optimization, compiler constructs object in desired location begin with. 1 of few situations standard allows optimization though affects observable behavior of program (since can tell whether copy constructor called).
  • nothing modified code requires copy elision, , nothing original code forbids it; 2 versions happen differ in whether trigger optimization in compiler under current settings.
    • note: situation here changes bit in c++17, optimization become mandatory in cases. see above link details.

edited add: incidentally, in version explicit copy constructor, constructor unusual in taking non-constant reference. means can't used anyway, since non-constant reference can't bind temporary test(1). think oddness may have why compiler performing copy elision. if change constructor take constant reference, implicitly-declared copy constructor would, may see behavior expecting, explicit copy constructor being called , destructor being called twice. (but that's speculation on part; you'll have try , see!)


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -