c++ - What does the const keyword do in an operator definition? -
i don't understand const keyword used in front of return type , after parameter list of operator definition. taken example book.
const char& operator [] (int num) const { if (num < getlength()) return buffer[num]; }
the c++ const
keyword means "something cannot change, or cannot delegate operations change onto other entities." refers specific variable: either arbitrary variable declaration, or implicitly this
in member function.
the const
before function name part of return type:
const char&
this reference const char
, meaning not possible assign new value it:
foo[2] = 'q'; // error
the const
@ end of function definition means "this function cannot change this
object , cannot call non-const functions on any object." in other words, invoking function cannot change any state.
const char& operator [] (int num) const { this->modifysomething(); // error buffer.modifysomething(); // error return buffer[num]; }
the goal of const
-correctness big topic, short version being able guarantee immutable state immutable. helps thread safety , helps compiler optimize code.
Comments
Post a Comment