c++referencec++98temporarytemporary-objects

When binding a const reference to a temporary object, why is the destructor called twice?


After reading this article on Herb Sutter's blog, I experimented a bit and ran into something that puzzles me. I am using Visual C++ 2005, but I would be surprised if this was implementation dependent.

Here is my code:

#include <iostream>

using namespace std;

struct Base {
    //Base() {}
    ~Base() { cout << "~Base()" << endl; }
};

int main()
{
    const Base & f = Base();
}

When run, it displays "~Base()" twice... But if I un-comment the constructor, it displays it only once!

Does anyone have an explanation for this?


Solution

  • This IS implementation-dependent.

    The standard allows a copy to occur when binding a temporary to a const reference. In your case, VC++ performs a copy only when the constructor is implicitly defined. This is unexpected, but permitted.

    CWG Issue 391 - Require direct binding of short-lived references to rvalues has fixed this for C++11.