Wednesday, 13 July 2016

When constructor and destructor will be called for various object declaration methods in C++ classes?

 
Guess the output for C++11?


#include<iostream>

class ArrayNotFound
{
private:
       int id;
      
public:
       ArrayNotFound(int a)
       {
             std::cout<<"ArrayNotFound constructor called: "<<a<<std::endl;
             id=a;
       }          
       ~ArrayNotFound()
       {
             std::cout<<"ArrayNotFound destructor called: "<<id<<std::endl;
       }
};

int main()
{
/* C++11 - Assume move constructor is supported */
ArrayNotFound l_obj = ArrayNotFound(1);
const ArrayNotFound &l_ref_obj = ArrayNotFound(2);
ArrayNotFound &&rvalue_ref_obj = ArrayNotFound(3);
ArrayNotFound(4);
ArrayNotFound l_obj3 = ArrayNotFound(5);
ArrayNotFound l_obj2(6);
return 0;
}


Output:


ArrayNotFound constructor called: 1
ArrayNotFound constructor called: 2
ArrayNotFound constructor called: 3
ArrayNotFound constructor called: 4
ArrayNotFound destructor called: 4
ArrayNotFound constructor called: 5
ArrayNotFound constructor called: 6
ArrayNotFound destructor called: 6
ArrayNotFound destructor called: 5
ArrayNotFound destructor called: 3
ArrayNotFound destructor called: 2
ArrayNotFound destructor called: 1

EXPLANATION:


Usually destructor will be called immediately for temporary objects soon after the construction.
As said above, destructor for following declaration method will be called immediately

ArrayNotFound(4);

But In the following objects creation method, even though temporary objects is used to create objects, destructor will not be called immediately. This is because of move semantics concept in c++. Temporary objects created will be moved instead of copying and destroying the temporary object.


ArrayNotFound l_obj = ArrayNotFound(1);
const ArrayNotFound &l_ref_obj = ArrayNotFound(2);
ArrayNotFound &&rvalue_ref_obj = ArrayNotFound(3);
ArrayNotFound l_obj3 = ArrayNotFound(5);