简体   繁体   中英

What does the const keyword do in an operator definition?

I don't understand what the const keyword is used for in front of the return type and after the parameter list of this operator definition. This is taken from an example from a book.

const char& operator [] (int num) const
{
    if (num < getlength())
        return Buffer[num];
}

The C++ const keyword basically means "something cannot change, or cannot delegate operations that change onto other entities." This refers to a specific variable: either an arbitrary variable declaration, or implicitly to this in a member function.

The const before the function name is part of the return type:

const char&

This is a reference to a const char , meaning it is not possible to assign a new value to it:

foo[2] = 'q'; // error

The const at the end of the function definition means "this function cannot change this object and cannot call non-const functions on any object." In other words, invoking this 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 is a big topic, but the short version is being able to guarantee that immutable state actually is immutable. This helps with thread safety and helps the compiler optimize your code.

这意味着您正在调用此方法的实际对象不会更改,并且如果尝试更改它,则会出现编译器错误。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM