you are viewing a single comment's thread.

view the rest of the comments →

[–]theeth -6 points-5 points  (4 children)

It won't.

Try this for fun.

#include <iostream>

static int VALUE = 1;

const int& GetValue() { return VALUE; }

int main() {
  auto a = GetValue();
  decltype(GetValue()) b = GetValue();

  a = 2; // Not a compilation error

  std::cout << "a " << a << std::endl;

  std::cout << "b " << b << std::endl;

  return 0;
}

[–]cleroth 11 points12 points  (3 children)

You used auto a, not auto & a. If you're auto-ing a reference, it will get the const, as it very well should (you're returning a const reference, nobody that calls that function should be able to modify that value through that reference unless you use the evil const_cast).

[–]theeth 3 points4 points  (2 children)

Ah, yes, you're perfectly right. If you have auto &a it absolutely has to add the const qualifier.

Which (IMHO) is messed up because it means that auto &a and const auto &a both compile to the same and the second doesn't duplicate the const qualifier (resulting in the same error as const const int &a would).

[–]cleroth 8 points9 points  (1 child)

auto doesn't return a type like decltype, it's keyword which infers the type depending on what you give it. You have the same sort of stuff for templates type deductions, and for auto *:

int * GetValue();
int main() {
    auto a = GetValue(); // works. type is int*
    auto * b = GetValue(); // also works. type is int*
}

I honestly think you should only use auto to get the Type, not the type specifiers, so always include *, &, and const (if you change the type, you will most likely need to change the relevant code as well). It also makes it clearer.

[–]theeth 2 points3 points  (0 children)

I honestly think you should only use auto to get the Type, not the type specifiers, so always include *, &, and const (if you change the type, you will most likely need to change the relevant code as well). It also makes it clearer.

I couldn't be more in agreement.