Re: stream operator << overload resolution: temporaries vs non-tempora
"Paul" <vhr@newsgroups.nospam> wrote in message
news:7939245D-29F2-40F3-8E4F-5D0DE98EF5D6@microsoft.com
#include <fstream>
int main()
{
std::ofstream("test.txt") << "Hello!" << std::endl;
std::ofstream ofs("test.txt", std::ios_base::app);
ofs << "Hello!" << std::endl;
}
writes the following into "test.txt":
00417708
Hello!
Why would overload resolution be different for temporary and
non-temporary objects, unless I have misinterpreted the results?
This is a well known problem. The C++ standard actually requires this
behavior. To avoid surprises, don't use stream objects as temporaries.
The issue is that some overloads of operator<< are member functions of
ostream, and others are standalone functions. The standalone versions
take ostream parameter by non-const reference. It looks roughly like
this (drastically simplified):
class ostream {
public:
ostream& operator<<(const void*); // (1): print a pointer value
};
ostream& operator<<(ostream&, const char*); // (2): print a string
Now consider
std::ofstream("test.txt") << "Hello!";
According to C++ rules, a temporary cannot bind to a non-const
reference, so (2) is not a viable match and is not considered by
overloading resolution. But a non-const member function can be called on
a temporary, so (1) is chosen. Instead of printing the contents of the
string, it prints the address.
--
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