What does const mean following a function/method s

2019-01-10 19:27发布

问题:

This question already has an answer here:

  • Meaning of 'const' last in a function declaration of a class? 8 answers

According to MSDN: "When following a member function's parameter list, the const keyword specifies that the function does not modify the object for which it is invoked."

Could someone clarify this a bit? Does it mean that the function cannot modify any of the object's members?

 bool AnalogClockPlugin::isInitialized() const
 {
     return initialized;
 }

回答1:

It means that the method do not modify member variables (except for the members declared as mutable), so it can be called on constant instances of the class.

class A
{
public:
    int foo() { return 42; }
    int bar() const { return 42; }
};

void test(const A& a)
{
    // Will fail
    a.foo();

    // Will work
    a.bar();
}


回答2:

Note also, that while the member function cannot modify member variables not marked as mutable, if the member variables are pointers, the member function may not be able to modify the pointer value (i.e. the address to which the pointer points to), but it can modify what the pointer points to (the actual memory region).

So for example:

class C
{
public:
    void member() const
    {
        p = 0; // This is not allowed; you are modifying the member variable

        // This is allowed; the member variable is still the same, but what it points to is different (and can be changed)
        *p = 0;
    }

private:
    int *p;
};


回答3:

The compiler won’t allow a const member function to change *this or to invoke a non-const member function for this object



回答4:

As answered by @delroth it means that the member function doesn't modify any memeber variable except those declared as mutable. You can see a good FAQ about const correctness in C++ here



标签: c++ const