jeudi 30 septembre 2021

Discrimination When Using auto specifier to deduce the type of a Prvalue in C++

I am trying to understand why the C++ standard/compiler discriminates against the behavior of auto. The example that i have is as follows:

int main()
{
    
    const int i = 34;//top level const on rhs. i is const int
    const auto &p = i;// low level const on rhs. p is const int&
    
    
    auto &g = i;//g is const int& . In this case the compiler is able to deduce that only reference to const can be bound to a const int 
    
    //auto &k = 5;//but in this case the compiler is not able(allowed) to deduce that only a reference to const can be bound to a prvalue 
    
    return 0;
}

As seen in the above code example, the compiler is able/allowed to deduced the type of variable g since only a reference to const type can be bound to a const type whereas in the next case the compiler is not able to deduce the type of variable k even though only a reference to const type can be bound to a const type. Ofcourse a rvalue reference can also be bound to a prvalue or xvalue.

My question is that even though we have a lvalue reference to some auto deduced type then why is the C++ standard does not allow the compiler to deduce k as const int& just as in the case of variable g? This seems intuitive enough to me. Maybe there are some problems associated with this which any of you can tell me.

Edit

I know that top level const of the initializer are ignored. For example,

const int i = 5;
auto k = i; //k is deduced to be int because the top level const of the initializer i is ignored

My question is about the implicit addition/deduction of the low level const on the rhs.

Aucun commentaire:

Enregistrer un commentaire