views:

1020

answers:

2

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?

+13  A: 

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.

Amazing answer, thanks a lot Sir :)
Drealmer
Interesting. Will this result in object slicing in some cases?
John Dibling
"C++1x will fix this." oh dear, is that what they're calling the next standard now or is this a witty joke?
veefu
Can you point to where in the standard the copy is allowed?
David Rodríguez - dribeas
where in the standard is this?
jalf
ISO/IEC 14882 8.5.3 paragraph 5
Drealmer
John, no. Never. Drealmer, you're welcome :). veefu, you must have been living under a rock! ;)
I thought they were going to go ahead and call it C++0xa? :)
Zan Lynx
I hear C+1xx is going to fix everything.
Kyle
A: 

Im using mingw 3.14 gcc 3.4.5 and my objects are not being copied with or without constructors. any idea why? Would this cause the program to be memory-unsafe?

amado
In this case the compiler is allowed to completely elide the copy - it is not a problem, in fact itt is desirable behaviour.
anon
Exactly what I was hoping to hear! Thanks for the clarification.
amado