Michael Sparks said:
In this code, the temporary inside_t instantiated in main() goes out of
scope by the time we hit the next line.
MSVC 2003 doesn't complain about that even at the highest warning level. Is
it legal? If so, why?
Its your responsability to guarentee an object's scope and lifetime, not the
compiler's. In this case, the outside_t structure invokes a temporary
inside_t object by *default* since outside_t's constructor *requires* a
reference to some inside_t object.
The compiler needs not satisfy the existance of the inside_t object after
the outside_t's cstor was invoked.
<snip>
____________________
Lets define an inside_t object, pass it by reference in order to construct
your outside_t object (which then initializes the inside_ member with a
reference that actually refers to something real). Note that the inside_t
object is never "part-of" the outside_t object, yet its now destroyed last.
#include <iostream>
struct inside_t
{
inside_t() { std::cout << "inside_t cstor\n"; }
~inside_t() { std::cout << "inside_t d~stor\n"; }
};
struct outside_t
{
outside_t(const inside_t& r_inside) : inside_(r_inside)
{
std::cout << "outside_t cstor\n";
}
~outside_t() { std::cout << "outside_t d~stor\n"; }
const inside_t& inside_;
};
int main()
{
inside_t in; // cstor invoked
outside_t out(in); // cstor invoked, in passed by reference
// display member inside_
std::cout << "&out.inside_ = " << &out.inside_ << std::endl;
const outside_t& ref_out = out;
std::cout << "reference ref_out = " << &ref_out << std::endl;
std::cout << "in's address is " << &in << std::endl;
return 0;
}
_________
Think of it this way: write a letter, put it in an envelope with some
address specified and stick an appropriate postage stamp on it. Mail it.
Nobody is going to build a home/apartment at destination in order to
guarentee the delivery of that one piece of mail. A reference works exactly
in the same way.