JKop wrote:
unsigned int CheesePlain(void)
{
unsigned int const chalk = 42;
return chalk;
}
unsigned int& CheeseRef(void)
{
unsigned int const chalk = 42;
return chalk;
}
I imagine a worthwhile compiler will not compile CheeseRef, at least not
without giving you quite a few warnings. First, the return type is not
const correct. Second, you are returning a reference to a local variable.
int main(void)
{
unsigned int plain = CheesePlain();
unsigned int ref = CheeseRef();
}
Now, consider that the return type is not unsigned int, but some other class
name that prints out stuff via cout in its constructor, copy constructor,
assignment operator. Will you find that there's a difference in the two
separate printouts, ie. that the "plain" one will create one more temporary
than the reference version?
-JKop
Let me propose a slight modification that may or may not provide the
answers you are wanting.
unsigned int CheesePlain()
{
unsigned int const chalk = 42;
return chalk;
}
int main(void)
{
unsigned int &ref = CheesePlain();
unsigned int plain = CheesePlain();
}
I've swapped the order because I want to talk about them in this order.
The first assignment creates a temporary, and copies the value of
'chalk' into it. If, as you propose, these were objects with
constructors, the temporary's copy constructor would be called. The
lifetime of the temporary is the same as the lifetime of the reference
bound to it, so when ref goes out of scope at the end of main, the
destructor should be called.
The second assignment is actually a bit more complicated, and the
precise behavior is not defined. One version of what could happen goes
like this. A temporary is created to hold the return value, and 'chalk'
is copied into it (copy constructor). Then, the temporary is used to
initialize 'plain' (copy constructor). The temporary then gets
destroyed, and its destructor is called. However, the implementation is
allowed (but not required) to construct the return value directly into
'plain', *even if the copy constructor or destructor have side effects*
(such as printing something)! So, depending on your implementation, you
may or may not see the temporary getting constructed and destructed.
Alan