Re: cannot compile example 1-1 of "More Exceptional C++"
wei.niu@gmail.com wrote:
But when compiling "ofstream( "abv.txt", ios::binary | ios::out ) <<
123 " with VC7.1 no warn was reported.Why?
Below is my test code:
#include <fstream>
#include <iostream>
using namespace std;
void test( ostream &out )
{
out << 356 ;
}
int main( int argc, char **argv )
{
test( ofstream("aa", ios::binary | ios::out ) ) ;
ofstream( "abv.txt", ios::binary | ios::out ) << 123 ;
return 0 ;
}
When compiling with VC7.1,it reports the error of wrongly calling
function test.
The difference could be shown even simpler:
ostream(0) << "text"; // works
ostream(0) << string("text"); // fails to compile
The difference is that operator<< for char* is a member while the one for
string is a non-member function. As such, it behaves like any other
function, even non-overloaded operators as in your example. Now, the
difference is that you can call non-const memberfunctions on a temporary
but not otherwise bind them to a non-const reference.
The typical workaround is to use a member operator<< that does almost
nothing and then take the result (a non-const reference) to bind it to a
non-const reference:
ostream(0) << "" << string("text"); // works
ofstream out ;
ifstream in ;
(argc > 2
? out.open( argv[2], ios::binary | ios::out ),
static_cast<ostream&>( out )
: cout )
[...]
Does "static_cast<ostream&>( out )" generate a temporary reference
object?If true,why no warn is reported?
'out' is a reference to an ofstream, that cast only converts it to a
reference to an ostream - no temporaries are involved.
Uli
--
Sator Laser GmbH
Gesch?ftsf?hrer: Ronald Boers, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]