const and temporary

Im reading 'Thinking in C++' by Bruce Eckel and on chapter 8 about constants there is this code, which should be an error as accoring to Eckel the return of the function f() creates a temporary which is constant. However when I run it in Microsoft Visual C++ Express 2010 it passes without error or warning

Is the book out of date?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

class X{};

X f(){
    return X(); 
}

void g1(X&){} 
void g2(const X&){} 

int main(int argc, char* argv){
	
	g1(f()); // Book says this should be error as f() returns a temporary which are constant

	g2(f());

	return 0;
}
Alright, well the book is really vague it sounds like, and this example is useless

Really I hate completely antithetically understandable examples. You would NEVER do this. At least in all my years, I haven't.

f() returns a newly created instance of the X class, which, as I understand it, is then copied to your main function when it returns, the g1 function just takes the address of said returned object, does nothing with it, and returns nothing. Your object dies, and is never used, when the main function returns.

I would probably switch to a new book, just because examples like this without application are difficult to understand. I doubt it's really "out of date" however you could possibly have better luck with other books.

Really if you're this far, you could probably just start making applications and learning that way, which IMHO is a much better method of learning any programming language. It's easier to grasp and you get rewarded with working programs. Look at sample code, and continue asking for help. Sorry if I didn't really answer your question =]
This is due to a non-standard extension for VC++ that allows you do that:

Compiled with /W4 (Only max? Fail VC++) I get:
Warning	1	warning C4239: nonstandard extension used : 'argument' : conversion from 'X' to 'X &'


There is a switch in the options to turn it off...and then I get:
Error	1	error C2664: 'g1' : cannot convert parameter 1 from 'X' to 'X &'


As expected.
Ah okay, thanks for the replies. I had a feeling it was VC++ related.
^Yeah, I was confused at first too until I set my warnings to level 4 (which I suggest keeping them at as much as possible).
Last edited on
Topic archived. No new replies allowed.