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

后端 未结 11 2419
时光取名叫无心
时光取名叫无心 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:27

    Does the const-ness of Bar affect the const-ness of your Foo? Or are you just doing that because there's no way to distinguish the const Bar* vs Bar* versions? If this latter is the case, I'd just have one bar() that returned a Bar* and be done with it. Afterall, something that takes a const Bar* can take a Bar* just fine, anyway. Don't forget, the const-ness of the bar() methods is about Foo, not about Bar.

    Also, if you offer both const- and non-const Bar* and are happy to have Foo be non-const, willy-nilly, then the constness of your Foo (and thus the bar() methods) obviously isn't that important, you're just filling in const and non-const versions for the heck of it. In which case, if you allow a non-const version, again just offer /only/ that one, consumers of const will happily take a non-const. Just, the way you've got const and non-const going there, it looks like it doesn't make much difference to the program.

    If you want const Foo objects to be able to return both const and non-const Bars, then just make bar() const and return a non-const Bar.

    I don't know, I'd have to see more to give a real answer.

    Think through though, which const-nesses are truly connected, and whether your program needs both const Foos and non-const Foos. Allowing all possibilities willy-nilly, it seems like you haven't thought through what the program requires.

提交回复
热议问题