Modern-CPP-Programming icon indicating copy to clipboard operation
Modern-CPP-Programming copied to clipboard

Chapter 5, page 47 Wrong reason given for compile failure

Open AlanDeSmet opened this issue 1 year ago • 1 comments

In chapter 5 on page 47 are these lines:

void g(int& value) {} // value is never a nullptr

// ... irrelevant lines omitted ...

//g(3); // compile error "3" is not a reference of something

While it will fail to compile, I believe the reason given is incorrect. The problem is that the function needs value to be mutable, but a constant isn't. If instead g is defined as void g(const int& value) {} (adding a const), it compiles.

AlanDeSmet avatar Jan 25 '24 17:01 AlanDeSmet

thanks for reporting but I don't agree. See for example what gcc returns

error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'

Also, to show a bit more complex situation, consider the following code

struct A { int x; };

void f(A&) {}

f(A{3}); // x within A is mutable but we cannot use it here

so f(int&) fails because the argument is not a lvalue reference

federico-busato avatar Jan 25 '24 21:01 federico-busato