On Thu, Apr 26, 2012 at 12:05 PM, Evan Driscoll <drisc...@cs.wisc.edu> wrote: > This thread has already beaten a dead horse enough that the horse came back > as a zombie and was re-killed, but I couldn't help but respond to this part: > > > On 01/-10/-28163 01:59 PM, Adam Skutt wrote: >> >> Code that relies on the identity of a temporary object is generally >> incorrect. This is why C++ explicitly forbids taking the address >> (identity) of temporaries. > > > Except that C++ *doesn't* really forbid taking the address of a temporary, > at least indirectly: > > #include <iostream> > > int const * address_of(int const & x) { > return &x; > } > > int main() { > std::cout << address_of(1+2) << "\n"; > } > > That complies without warning with GCC 4.6 '-Wall -Wextra', MSVC 2010 '/W4', > and Comeau's online front end, and I am pretty confident that the above code > is perfectly legal in terms of provoking undefined behavior (in the > technical C++ sense of "your program is now allowed to set your cat on > fire").
Yes, you can get a const reference to a temporary object, but that's the only thing you can do. This is intentional, so you can use temporaries (e.g., std::string("Hello World") ) in the same contexts where one would use a literal (e.g., 3 or 4.2). Note that it's impossible to mutate the temporary and impossible for the reference to outlive the temporary. What the standard says is: "The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id." The unary & operator is known as the address-of operator. The C++ standard is actually going further than forbidding temporaries, it forbids rvalues, which are things one expects to see on the Right hand side of an assignment, or =. One of Scott Meyer's Effective C++ books covers all of this in great detail, including how you can get a temporary that's an lvalue as opposed to an rvalue. Adam -- http://mail.python.org/mailman/listinfo/python-list