简体   繁体   中英

making c++ variables const

I love "const". I wish every variable and method that "ought to be const" IS "const". The problem is that whether a variable or method "ought to be const" depends on methods/variables further down in the call tree. Is there some tool, or some process, for statically examining a body of code and doing "bottom-up en-const-ification"?

I don't know the answer to your question, but I would like to argue against the claim that

whether a variable or method "ought to be const" depends on methods/variables further down in the call tree

Actually, const should be on a logical level. Ie you should mark something const if it should not be changed logically. If it later is, then you will get a compiler error and will need to reconsider either the fact of changing or your initial assumption.

The rule is:

if something is const, it should not be changed

rather than

if something is not changed de facto, then let's make it const

There are various static analyser tools that can do that. Gimpel Flexelint comes to mind.

Having said which, it's possible to get results that don't seem quite right. For instance, given this:

class Wibble {
   Some_Implementation_Detail *stuff; //PIMPL idiom
  public:
   void set_something(int a) { stuff->set(a); }
};

then set_something can be made const . This is technically correct, but not very helpful, because it's not logically const at all in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM