Should I declare method "const" if it is "shallow const" only, not "deep const"?
Asked Answered
U

1

5

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?

Underbred answered 28/6, 2020 at 20:5 Comment(6)
Hope this explains it: https://mcmap.net/q/216315/-what-is-const-void-and-is-it-a-valid-return-typeHiga
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.Pellet
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.Furunculosis
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.Intercalate
@Intercalate 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.Patch
What does "shallow const" mean??Kumiss
A
8

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).

Awad answered 28/6, 2020 at 20:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.