2
votes

I have class Foo and its member bar_ is a pointer to some data. Method modify modifies the data, but not the pointer itself. Therefore I can declare the method as const:

class Foo {
public:
    Foo() : bar_(new double) {};
    void modify() const {*bar_ += 1;};
private:
    double *bar_;
};

If I declare the method as const, it will accessible from other const methods, which is more flexible. At the same time I can drop const as a hint for other developers and users that method modifies the data indirectly (and let think that the data is owned by the class). So I have a choice here: declare modify as const or drop const: void modify() const or void modify().

What are pros and cons of each approach? What do guidelines say? What should I do?

1
There is no universal law that says where the class method should or should not be const here. This is up to you to decide.Sam Varshavchik
Classes can have mutable members that const functions can modify. Whether or not a function should be const really depends on whether it is "logically const" - doesn't modify the object in any meaningful observable way.Jesper Juhl
With modern C++, as per Herb Sutter, the const is also supposed to be robust for multithreading. So having mutable state with const ought to be a strong guarantee of safe logical const. And that's a bit more work, such as using atomic or mutex protection.Eljay
@Eljay At least it's generally a good idea since multithreading is a thing. Still, not making a component thread-safe can be a significant cost-saving.Deduplicator

1 Answers

6
votes

const after a method declaration is a statement of intent - const methods are meant to be idempotent; they do not modify the state of the object and can be called on const instances.

If the value pointed-to by bar_ is part of the object's state, then a const method should not modify it.

In addition, even the name modify() sounds like it modifies the object in some way, and thus should not be declared const.

But also the other way is important - if a method does not modify the state, it is recommended to declare it const (see C++ Core Guideline Con.2).