What do member function qualifiers (other than const) mean?

232 views Asked by At

It's common knowledge that class methods can be qualified with const - and if they are, they're not allowed to change the instance they're called for (ignoring mutable etc). One can think of it as though the member function was freestanding, but getting a this pointer as its first parameter - which would be const MyClass* for a const method, and MyClass ptr otherwise.

I've recently become aware that there are actually additional possible qualifiers for member functions (see, e.g. this question on the site), so the qualifiers are:

  • const or non-const
  • volatile or non-volatie
  • unreferenced, regular reference (&) or rvalue-reference (&&)

About volatile, I know what that means for variables - you can't just make a copy (e.g. in a register or maybe in some non-coherent cache) and expect it to be valid, as other code might be changing the original location. This doesn't seem to apply very cleanly to the "this pointer metaphor" like the const modifier, since - it's a pointer, of course others can change the pointed-to data. I would better understand something like a __restrict__ qualifier on this. So, is volatile what I'm assuming it to be or am I misinterpreting?

Now, about the reference qualifiers for members - I'm clueless. What would that even mean? What would be a reference to what? I don't get it.

1

There are 1 answers

1
Argenet On

"volatile" keyword effectively tells compiler to restrain from any assumptions it can usually do in order to optimize the generated assembler instructions to deal with a particular variable.

Reference qualifiers are used to make this method be only called when the object it is called on is an lvalue reference (for &) or rvalue reference (for &&) accordingly. This helps if you want to alter the behaviour of your method based on lvalueness/rvalueness of the objects (e.g., given that rvalues are typically short-lived temporaries).