I recently had a discussion where we argued if it is a good idea to make everything const if possible.
The argument did go like that: If I expose an internal part of the class by returning a non-const reference to it, I should not make that getter const even if it is possible.
For example:
class Foo
{
std::unique_ptr<int> bar;
public:
Foo()
: bar{std::make_unique<int>(10)}
{
}
int& getBar() const // <-- we argued about that const here
{
return *bar;
}
};
int main()
{
const auto foo = Foo{};
foo.getBar()++;
}
The code from above only works because the int
is not stored within the memory of Foo
itself. If I would replace the unique_ptr
with a normal int
but keep the public interface of the class the same the compiler will output an error:
class Foo
{
int bar;
public:
Foo()
: bar{10}
{
}
int& getBar() const
{
// error: binding reference of type 'int&' to 'const int' discards qualifiers
return bar;
}
};
int main()
{
const auto foo = Foo{};
foo.getBar()++;
}
Is it a good idea to intentionally make a getter function non-const if it exposes something internal of the class as a non-const reference?