0

What does the second const do in the structure below? (it's just an example function).

I understand that the first const makes the function return a constant object. But I can't figure out what the const before the identifier does.

First I though that it returned a constant pointer to a constant object, but I'm still able to reassign the returned pointer, so I guess that isn't the case.

const SimpleClass * const Myfunction()
{
   SimpleClass * sc;
   return sc;
}
  • 4
    http://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const – Cody Gray - on strike Mar 05 '16 at 16:47
  • 1
    It *does* return a constant pointer to a constant object. You can copy the *value* of that pointer to a non-const variable. (It's the same principle as `const int f() { return 0; } int main() { int x = f(); x = 1; }`.) – molbdnilo Mar 05 '16 at 16:52
  • Want another *const*? Add it at the end of the MyFunction() line. ;) – tofro Mar 05 '16 at 17:53

2 Answers2

3
const SimpleClass * const Myfunction()
{   
    return sc;
}

decltype(auto) p = Myfunction();
p = nullptr; // error due to the second const.

But the truth is that not many people uses decltype(auto), and your function will be normally called like:

const SimpleClass *p = Myfunction();
p = nullptr; // success, you are not required to specify the second const.

const auto* p = Myfunction();
p = nullptr; // success, again: we are not required to specify the second const.

And...

const SimpleClass * const p = Myfunction();
p = nullptr; // error

const auto* const p = Myfunction();
p = nullptr; // error
Jts
  • 3,447
  • 1
  • 11
  • 14
2

Second const means that returned pointer is constant itself whereas first const means that memory is unmodifiable.

Returned pointer is temporary value (rvalue). That's why it doesn't matter whether it's const or not since it cannot be modified anyway: Myfunction()++; is wrong. One way to "feel" second const is to use decltype(auto) p = Myfunction(); and try to modify p as José pointed out.

You might be interested in Purpose of returning by const value? and What are the use cases for having a function return by const value for non-builtin type?

Community
  • 1
  • 1
George Sovetov
  • 4,942
  • 5
  • 36
  • 57