简体   繁体   English

使c ++变量为const

[英]making c++ variables const

I love "const". 我爱“const”。 I wish every variable and method that "ought to be const" IS "const". 我希望“应该是const”的每个变量和方法都是“const”。 The problem is that whether a variable or method "ought to be const" depends on methods/variables further down in the call tree. 问题是变量或方法“应该是const”取决于调用树中进一步向下的方法/变量。 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 变量或方法“应该是const”是否取决于调用树中进一步向下的方法/变量

Actually, const should be on a logical level. 实际上,const应该在逻辑层面上。 Ie you should mark something const if it should not be changed logically. 即如果不应该逻辑地改变,你应该标记const。 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. 想到Gimpel Flexelint。

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 . 然后set_something可以成为const This is technically correct, but not very helpful, because it's not logically const at all in this case. 这在技术上是正确的,但不是很有用,因为在这种情况下它根本不是逻辑上的const

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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