federico-busato / Modern-CPP-Programming

Modern C++ Programming Course (C++03/11/14/17/20/23/26)

Home Page:https://federico-busato.github.io/Modern-CPP-Programming/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Chapter 5, page 47 Wrong reason given for compile failure

AlanDeSmet opened this issue · 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.

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