Question

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?

Was it helpful?

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.

C++1x will fix this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top