Re: stream operator << overload resolution: temporaries vs non-tem
"Paul" <vhr@newsgroups.nospam> wrote in message
news:F8312E9E-01F7-4278-BE98-E0A1A2B86EDF@microsoft.com
Thank you, Igor, I have indeed missed on that. But this still does not
explain a couple of things, I think.
1) Why would it work for strings (std::string): string operator
functions too take a reference to a stream:
As an extension, MSVC allows binding temporaries to non-const
references. This conversion is the lowest ranking one, only used when no
other alternative is available. Try building with /Za (strict ANSI
conformance), you should get an error.
std::ostream& operator <<(std::ostream&, const std::string&);
std::ofstream("test.txt") << std::string("Hello!") << std::endl;
(I debugged and checked: it does call the above operator << for
strings.)
Don't you get a warning about a non-standard feature being used?
2) Why would it work on subsequent insertions:
std::ofstream("test.txt") << "Hello!" /*returns address*/ << ' ' <<
"Hello!" << std::endl;
The subsequent insertion is called on a reference returned by the
previous insertion. The compiler has no way to know this reference
refers to a temporary. Consider:
struct C {
C& detemporize() {return *this;}
};
void f(C&);
// does not compile: can't bind temporary to non-const reference
f(C());
f(C().detemporize()); // works
If the stream is treated as a constant object:
const std::ofstream& tmp = std::ostream("test.txt");
tmp << "Hello!";
then the reference to the stream returned from this operation will
also be a constant?
This should not compile - you can't call non-const function through a
const reference.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925