How to generate a non-const method from a const method?

后端 未结 11 2460
时光取名叫无心
时光取名叫无心 2021-02-08 11:18

While striving for const-correctness, I often find myself writing code such as this

class Bar;

class Foo {
public:
  const Bar* bar() const { /* code that gets          


        
11条回答
  •  深忆病人
    2021-02-08 11:39

    Your code implies that the const bar() is actually creating and returning a new Bar, and I find that peculiar if you're doing that lot.

    For me a bigger problem is that constness in a member function is limited to reference and non-pointer members. The moment you have (non-const) pointer members, a const function can change them even though it claims to be const on the box.

    If your Bar instance is a member variable, consider returning a reference instead.

提交回复
热议问题