1

I could not understand the output of the following test program, why d1 is not destructed at the end of incDate(). And why the copy constructor is not called.

The output is,

constructing 0xbf9be858

constructing 0xbf9be85c

Marker

destructing 0xbf9be85c

destructing 0xbf9be858

Test program is,

class Date
{
    int days;
public:
    Date();
    Date(const Date&);
    Date incDate();
    ~Date(){cout<<"destructing "<<this<<endl;}
};

Date::Date()
{
    cout<<"constructing " << this <<endl;
    days=0;
}

Date::Date(const Date& aDate)
{
    cout<<"copy constructing " << this <<endl;
    days = aDate.days;
}

Date Date::incDate()
{
    Date d1;
    d1.days++;
    return d1;
}

int main()
{
    Date d1;

    Date d2 = d1.incDate();
    cout<<"Marker"<<endl;
}
user2179277
  • 51
  • 1
  • 3
  • 1
    It's called [(named) return value optimization](https://en.wikipedia.org/wiki/Return_value_optimization). If you're using gcc or clang, pass the `-fno-elide-constructors` flag to the compiler. – Praetorian Jan 09 '15 at 04:37

0 Answers0