简体   繁体   中英

Why use const int parameter when overloading the subscript operator?

I am new to C++ so can you please explain why/when should I use this

int & MyArray::operator[] (const int i)
{
    return arr[i];
}

instead of this

int & MyArray::operator[] (int i)
{
    return arr[i];
}

It's doesn't make a huge amount of difference!

Some people like to treat parameters as immutable, so they flag them as const . In this case it's a stylistic thing.

In a function declaration , it makes absolutely no difference, because top-level const s are ignored.

These two are actually the same declaration, and for that reason, top level const in function parameters should be avoided:

void foo(int);
void foo(const int); // re-declaration of above function

In a function definition , it means you cannot change the copy of the argument in your function:

void foo(int i) { i++; } // OK
void foo(const int i) { i++; } // Error

So, it can be used as an implementation artifact, to express that the local variable is const . This gives the compiler more scope to perform optimizations.

Don't do this. It's identical from caller's perspective and just adds visual noise.

The parameter i is passed by value and is a plain data type, it is copied, so when you mark it as const you are telling the compiler that it cannot change inside the method, but since it is a copy it isn't important at all, and in this specific example you are just using it as an index.

Both forms are correct. Use the first one if you want to ensure that the "i" parameter will not be modified in the function, which may be useful if the function is longer/more complicated. However, in the declaration of the operator do not use const:

int& operator[](int i);

It is legal to have declaration without const, and definition with it.

作为一种规则,任何你不打算修改的都应该是const

If you not trying to edit your parameter then its better to use const .

As far as performance is concerned not much difference. But it safeguards your parameter from editing ( accidentally ) inside function.

int & MyArray::operator[] (const int i)

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