Posts

Showing posts with the label const

Difference between const auto & and auto & if object of reference is const

// case 1 const int i = 42; const auto &k = i; // case 2 const int i = 42; auto &k = i; Do we need the const keyword before auto in this scenario? After all, a reference (k) to an auto-deduced type will include the top level const of the object (const int i). So I believe k will be a reference to an integer that is constant (const int &k) in both cases. If that is true, does that mean that const auto &k = i; in case 1 is replaced by the compiler as just const int &k = i; (auto being replaced with int)? Whereas in case 2, auto is replaced with const int? auto keyword automatically decides the type of the variable at compile time. In your first case, auto is reduced to int where it's reduced to const int in the second case. So, both of your cases are reduced to the same code as: const int &k = i; However, it's better to have the const explicitly for better readability and to make sure your variable TRULY is const. Type deduction with auto works l...

Why can const char* const & = “hello” compile?

I am reading a code snippet from a book and find this: const char* const & a = "hello"; //can compile const char*& a = "hello"; //cannot All I know is that when initializing a reference, the array to pointer conversion would not take place. const char* const &, a reference to a const pointer, the pointer points to const char. const char*&, a reference to a pointer, the pointer points to const char. So why does adding an extra const, indicating that the pointer is a const, allow it to compile? It's essentially adhering to this formula T const & a = something_convertible_to_T; Where T is const char*. In the first case, a temporary pointer can be materialized, assigned the address of the literal, and then have itself bound to the reference. In the second case, since the lvalue reference isn't const, it can't happen. Another example of more of the same const char* && a = "hello"; // rvalue ref makes a no into a yes....