Jul 19, 2013

[C++][NOTE][ORIGINAL] Temporary Object Life Time Gotya

C++11 ISO/IEC 14882:2011
(12.2.4) 

There are two contexts in which temporaries are destroyed at a different point than the end of the full expression. 

  • The first context is when a default constructor is called to initialize an element of an array. 
    • If the constructor has one or more default arguments, the destruction of every temporary created in a default argument is sequenced before the construction of the next array element, if any.


#include <iostream>

using namespace std;

struct Argument
{
   Argument()
   {
      cout << "Argu Constructor" << endl;
   }

   ~Argument()
   {
      cout << "Argu Destructor" << endl;
   }
};

struct Picacho
{
   Picacho(Argument=Argument())
   {
      cout << "Picacho Constructor" << endl;
   }
};


int main(){
   Picacho pica[10] = {Picacho()};
}



Result:
Argu Constructor
Picacho Constructor
Argu Destructor
Argu Constructor
Picacho Constructor
Argu Destructor
Argu Constructor
Picacho Constructor
Argu Destructor
Argu Constructor
Picacho Constructor
Argu Destructor
Argu Constructor
Picacho Constructor
Argu Destructor
Argu Constructor
Picacho Constructor
Argu Destructor
Argu Constructor
Picacho Constructor
Argu Destructor
Argu Constructor
Picacho Constructor
Argu Destructor
Argu Constructor
Picacho Constructor
Argu Destructor
Argu Constructor
Picacho Constructor
Argu Destructor

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.