views:

139

answers:

2

Are the following two statements semantically same?

#1 person p("Rahul", 20);

#2 person const &p = person("Rahul", 20);

EDIT:

Sorry, I meant to ask whether the following two are semantically same:

#1 person const p("Rahul", 20);

#2 person const &p = person("Rahul", 20);

+5  A: 

No they are not. The way that p behaves in each case is different. For example, in the latter case, you could not say:

p.rename( "fred" );

assuming person had a rename() method.

Of course, if your first instance had been:

const person p("Rahul", 20);

the two would have been much more similar. I hope you are not intending using references for all your "variables" :-)

anon
So they are similar, not same?
missingfaktor
@Rahul With the const version, I can't think of a way of telling them apart, but I'm sure someone else will come up with something.
anon
You can define a reference to (what appears to be) a temporary, and that temporary sticks around? I didn't know that.
Ari
@Ari Yes you can, otherwise reference function parameters that refer to temps wouldn't work.
anon
I'm not talking about creating the reference, I was surprised about the temporary surviving after the statement in which it is created. When calling a function with references to temps, the expression's evaluation ends after the function returns.
Ari
Temporaries can be bound to const references and persist for the lifetime of the reference, but function arguments are one of the exceptions - see *§12.2/5* for details.
Georg Fritzsche
@Ari: http://stackoverflow.com/questions/75538/hidden-features-of-c/76606#76606
missingfaktor
+2  A: 

They are not. However, the difference are affected only by the fact that the second case needs a copy constructor to be accessible in C++03 (even if the copy constructor call is not actually done)

// works with #1 fails with #2
struct f1 { f1(string, int); private: f1(f1 const&); };
Johannes Schaub - litb