简体   繁体   中英

C++ Function Const

I have a class which I am using to try and help understand the concept of const. For example.

Class class1:
{
protected:
    double * info;
public: 
    void set(const int i, const int j, const double val) const
    {
          info[i + j] = val;
    }
}

I have read multiple articles that say you write const after a class function if that function isn't going to change any member variables. With this class however it works is it correct or incorrect?

Also my understanding of const variables is that you make them const if they are never going to change, but is there any benefit to this?

Thank you, apologies if this has been answered elsewhere i just can't seem to get my head around it.

Just to add some color to already provided answers. Withing const qualified functions, all mebers effectively becoming const. For example, your info is becoming const and behaves as if it was defined like this:

double* const info;

Note, that this IS different from

const double* info;

First makes info itself unmodifiable (you can't say info = &d , but you can say *info = 42 . On the other hand, the later means info is modifieable, but not where it points to. You can write info = &d , but not *info = 42 .

Obviously, there is a way to have both qualities, by saying const double* const info - that would prevent modifications of both pointer and the value. However, this is not what const -qualification does for function. Is it intuitive? I dare say, it is not. However, this is what it is, so we have to live with that.

Obviously, one could argue that const-qualified functions could make all member pointers double-const, but what about pointer-like objects (say, unique_ptr )? There is no way compiler would be able to make those double const, so it is better to be consistant.

It is sort of correct, a const member function doesn't alter internal state. set obviously doesn't alter the pointer info , but does alter what it points to. Now your have to decide (the compiler can't) if this is const behavior or not. In most cases it wouldn't be const behavior.

This function doesn't change any member variables. The only member variable is info , which it doesn't change. It does change the thing info points to , but that's not a member variable. So it's legal as far as the compiler's concerned.

However, note that it's likely to confuse other programmers (including yourself in six months) - generally, const functions shouldn't modify the object's state.

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