Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why const is ignored in auto keyword on constant reference

Tags:

c++

auto

int main()
{

    int a = 10;
    const int &b = a;
    int &c = b; //gives error : C should a  reference to a const b 
    auto d = b; // why const is ignored here?
    d = 15;
    cout << a << d;
}

In c++ Primer, it's mentioned that "const in reference type is always low-level " Then how come auto d = b is not constant?

like image 225
samnaction Avatar asked Oct 12 '25 23:10

samnaction


1 Answers

Because the type deduction rules for auto deduce to an object type. You are copy initializing a new int from the one referenced by b.

That's by design. We want to create new objects without explicitly specifying their type. And more often than not, it's a new object that is a copy some other object. Had it deduced to a reference, it would defeat the intended purpose.

If you want the deduced type to be a reference when the initializer is a reference, then that is accomplished with a placeholder of decltype(auto):

decltype(auto) d = b; // d and b now refer to the same object
d = 15; // And this will error because the cv-qualifiers are the same as b's
like image 64
StoryTeller - Unslander Monica Avatar answered Oct 14 '25 12:10

StoryTeller - Unslander Monica