Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : Different deduction of type auto between const int * and cont int &

Tags:

c++

c++11

Here are the code samples.

a. int ii = 0;
b. const int ci = ii;
c. auto e = &ci; --> e is const int *
d. auto &f = 42; --> invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
e. const auto &g = 42 --> ok

Observation:
1. for clause c) the type const is automatically deduced
2. for clause d) the type const is not automatically deduced
3. for clause e) the type const has to be added manually in order for it to work.

Why type const is automatically deduced for clause c but not d?

like image 775
yapkm01 Avatar asked Feb 08 '23 22:02

yapkm01


2 Answers

The reason is not the const-ness, but the r-value-ness.

You can't take a non-const reference to an r-value.

If you wonder what's an r-value, the original idea was something that can only be at the right side of an assignment.

To take the address of a compile-time constant the compiler first copies it, and gives you that address. To enable that behavior, the reference must explicitly be const.

To complete the answer: case

  • c) the type of ci is const int, thus the type of &ci is address of const int.
  • d) The type of 42 is int. auto deduces to int, f is declared a reference to int, but fails to bind to r-value
  • e) The type of g is const int &, which can bind to compile time constant.
like image 73
TheCppZoo Avatar answered Feb 16 '23 03:02

TheCppZoo


That's because the type of 42 is not const int, it's int. It's an rvalue, which means it cannot bind to an lvalue reference (unless it's a reference to const), but it's still of type int. So that's what auto deduces to.

If you try it with ci instead of 42, you'll find it works:

auto &e = ci;
like image 38
Angew is no longer proud of SO Avatar answered Feb 16 '23 03:02

Angew is no longer proud of SO