Is the book <<Thinking in C++>> Wrong?

This is a discussion on Is the book <<Thinking in C++>> Wrong? within the C++ Programming forums, part of the General Programming Boards category; An example in the book Thinking in C++: Code: class X{}; X f() { return X(); } void g1(X&){} void ...

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    284

    Is the book <<Thinking in C++>> Wrong?

    An example in the book Thinking in C++:

    Code:
    class X{};
    
    X f() {
    	return X();
    }
    
    void g1(X&){}
    void g2(const X&){}
    
    
    int main(){
    
    	g1(f());
    	return 0;
    }
    According to the book the compiler should report error because f() returns a temporary object which is defined by the compiler as "const".
    However I compile this code using VS 2005 it works. Is the book wrong?

    Thanks!

  2. #2
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,239
    The book is not wrong. The compiler is wrong.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,589
    That is probably due to a too low warning level. I upped my warning level to /W4 and was informed:
    Code:
    warning C4239: nonstandard extension used : 'argument' : conversion from 'X' to 'X &'
            A non-const reference may only be bound to an lvalue
    So what you see is nonstandard, and Thinking in C++ is correct.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    The larch
    Join Date
    May 2006
    Posts
    3,573
    VC++ seems to be kind of lax with constness of temporaries. In the current project I had some function prototypes like
    Code:
    void foo(SomeObject&);
    And I called them like this:
    Code:
    foo(SomeObject(x, y, x));
    MingW however requires SomeObject to be const in the function prototype for this to work.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ Templates book discussion
    By manutd in forum C++ Programming
    Replies: 38
    Last Post: 01-18-2007, 02:56 PM
  2. Must read book!
    By RealityFusion in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 07-15-2004, 09:05 PM
  3. Should i get a new reference book?
    By Raison in forum Windows Programming
    Replies: 2
    Last Post: 06-15-2004, 10:43 PM
  4. I"m selling a book...
    By St0rmTroop3er in forum Game Programming
    Replies: 2
    Last Post: 12-13-2003, 12:55 PM
  5. C++: Reference Book, GUI, Networking & Beyond
    By kuphryn in forum C++ Programming
    Replies: 4
    Last Post: 11-10-2001, 07:03 PM

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