标记所有不修改const的变量是否有不利之处? [英] Are there any downsides to marking all variables you don't modify const?

查看:70
本文介绍了标记所有不修改const的变量是否有不利之处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过大量的搜索之后,我发现了很多关于将函数及其参数标记为 const 的信息,但是没有有关将变量标记为 const的指南

After much googling I've found a lot about marking functions and their parameters as const, but no guide on marking variables as const.

这是一个非常简单的示例:

Here's a really simple example:

#include <string>
#include <iostream>

void example(const std::string& x) {
  size_t length = x.length();
  for (size_t i = 0; i < length; ++i) {
    std::cout << x.at(i) << std::endl;
  }
}

int main() {
  example("hello");
}

为什么不赚钱

size_t length = x.length();

const like

const like

const size_t length = x.length();

按惯例?

我知道这样一个小而简单的示例确实并没有显示出任何大的好处,但是似乎在较大的代码库中很有用,在该代码库中,您可能会偶然地突变了不应该突变的变量。

I know such a small, simple example really doesn't show any huge benefit to this, but it seems like it'd be helpful in a larger codebase where you might accidentally mutate a variable you shouldn't have mutated.

尽管有这样的好处,但我并没有真正看到它使用太多(在我见过的C ++代码库中),也几乎没有提到使函数及其参数 const

Despite that benefit, I don't really see it used that much (in the C++ codebases I've seen) or mentioned nearly as much as making functions and their parameters const.

除了必须输入5个额外字符以外,这样做还有其他缺点吗?我没有在这个主题上找到太多东西,如果有这么多const的问题,我也不想to脚。

Is there some downside to doing this other than having to type 5 extra characters? I haven't found much on the topic, and I don't want to shoot myself in the foot if it's a problem having so many consts.

推荐答案

标记没有修改的变量没有任何缺点 const

There are no downsides to marking variables you don't modify const.

有但是有一些好处:编译器将帮助您诊断,当您无意中修改了您不应该/不想要的变量时,编译器可能(尽管由于该语言的 const_cast mutable 这种情况很少)会生成更好的代码。

There are some up-sides though: the compiler will help you diagnose when you unintentionally modify a variable you shouldn't/didn't mean to and the compiler may (although due to the language having const_cast and mutable this is rare) generate better code.

因此,我建议;在可能的地方使用 const 。没有缺点,编译器可以帮助您发现错误。没有理由(除了一些额外的输入)。

So, I'd advise; use const where you can. There are no downsides and your compiler can potentially help you spot bugs. No reason not to (except for a bit of extra typing).

请注意,这也扩展到成员函数。尽可能使它们为 const -它使它们可以在更多上下文中使用,并帮助用户推理代码(调用此函数不会修改对象是宝贵的信息)。

Note that this extends to member functions as well. Make them const when you can - it lets them be used in more contexts and helps users reason about the code ("calling this function won't modify the object" is valuable information).

这篇关于标记所有不修改const的变量是否有不利之处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆