对局部变量使用 const 是否被认为是好的做法?

发布于 2024-10-01 16:14:45 字数 1079 浏览 1 评论 0原文

最近几周,我发现自己到处都使用了很多 const。不仅在方法或参数声明中,甚至在临时变量中也是如此。

让我用一个简单的函数来说明。

我曾经写过:

// A dummy function that sums some computation results
unsigned int sum_results(const Operation& p1, const Operation& p2)
{
  unsigned int result1 = p1.computeResult();
  unsigned int result2 = p2.computeResult();

  // Well this function could be in one single line but
  // assume it does more complex operations
  return result1 + result2;
}

但现在更像是:

// A dummy function that sums some computation results
unsigned int sum_results(const Operation& p1, const Operation& p2)
{
  const unsigned int result1 = p1.computeResult();
  const unsigned int result2 = p2.computeResult();

  // Well this function could be in one single line but
  // assume it does more complex operations
  return result1 + result2;
}

后者对我来说更有意义,而且似乎更不容易出错。 (我承认在这个例子中,这并不重要)但是我见过很少代码示例,其中 const 用于临时/局部变量。我想了解为什么。

有什么原因导致这种情况不常见吗?我是否滥用了 const ?或者只是我一直在看错误的样本?

These last weeks, I found myself using a lot of const everywhere. Not only in methods or arguments declarations, but even for temporary variables.

Let me illustrate with a simple function.

I used to write:

// A dummy function that sums some computation results
unsigned int sum_results(const Operation& p1, const Operation& p2)
{
  unsigned int result1 = p1.computeResult();
  unsigned int result2 = p2.computeResult();

  // Well this function could be in one single line but
  // assume it does more complex operations
  return result1 + result2;
}

But now it is more like:

// A dummy function that sums some computation results
unsigned int sum_results(const Operation& p1, const Operation& p2)
{
  const unsigned int result1 = p1.computeResult();
  const unsigned int result2 = p2.computeResult();

  // Well this function could be in one single line but
  // assume it does more complex operations
  return result1 + result2;
}

The latter makes more sense to me and seems less error prone. (I admit that in this example, it doesn't really matter) However I've seen very few code samples where const was used on temporary/local variables. And I'd like to understand why.

Is there any reason why this isn't a common case ? Am I abusing with my use of const ? Or is it just me that has been looking at the wrong samples ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

巡山小妖精 2024-10-08 16:14:46

我个人认为 const 永远不会太多,而且我大量使用它们作为局部变量。我可以添加const但不添加的唯一上下文是内置类型的参数:

void foo(const int);

在这里,我相信(但这实际上是个人品味的问题)它毫无用处地使界面变得混乱。

I would personally say that there never are too many const, and I use them abundantly for local variables. The only context where I could add a const but don't is on parameters of built-in types :

void foo(const int);

Here, I believe (but that's a matter of personal taste really) that it uselessly clutters the interface.

§对你不离不弃 2024-10-08 16:14:46

我不认为这纯粹是程序员偷懒的情况——简洁也是一个考虑因素。有些人可能会发现int x;比“const int x;”的精神负担要少。在查看功能时:额外的空间可能有助于他们在旁边添加注释。我提到这一点并不是作为建议,而是因为我认为了解影响人们态度的所有“成本”很重要,因为人们在这里不始终使用 const 确实令人困惑。

考虑到在函数中使用变量的某些时候,可能有必要对其进行调整,这一点也很有趣。例如,您计算一些内容,但随后您进入一些 if 语句和事物,并且存在一些边缘情况,您需要从字符串中删除尾随元素、处理相差一问题、清除值等。如果您最初将变量设置为 const,那么您的工作流程会被更多地中断,以返回到定义并从定义中删除 const,然后将光标返回到您正在工作的位置。与此相反,尽可能使用 const 的习惯是一个危险信号,因为一些此类调整隐藏在函数体中,并且对于以后的理解和维护非常有用。

尽管如此,我仍然积极鼓励您继续使用 const:我通常会这样做并认为这是最佳实践。其原因显然您已经了解,并且已在其他答案中列举。

I don't think it's purely a case of programmers being lazy - concision is also a consideration. Some people may find int x; less mental load than "const int x;" when reviewing the functions: that bit extra space might help them fit a comment alongside. I mention that not as a recommendation, but because I think it's important to understand all the "costs" that factor into peoples' attitudes, as it really is confusing that people don't consistently use const here.

It's also interesting to consider that at some point in using a variable in a function, it may become necessary to tweak it. For example, you calculate something, but then you go into a few if statements and things and there's some edge case where you need to remove a trailing element from a string, handle an off-by-one issue, clear the value etc.. If you had initially made the variable const, then your workflow is interrupted more to return to and remove const from the definition, then return the cursor to where you're working. Countering this, a habit of using const where possible is a red flag that some such tweaks are hidden in the function body, and very useful for later understanding and maintenance.

Still, I actively encourage you to continue to use const: I typically do so and consider it best practice. The reasons for that are obviously understood by you, and have been enumerated in other answers.

热血少△年 2024-10-08 16:14:46

在 C++ 中,如果可以的话,这是一种常量变量的好方法。但话虽如此,在变量作为参数传递或在不同代码段(如类变量)之间共享的情况下,这更有意义。主要思想是阻止其他代码意外修改变量,这些代码不知道该变量不应被更改。

因此,鉴于上述情况,对于函数的局部变量,将它们组合起来有点矫枉过正。然而,这样做并没有什么害处。

In C++, this is a good approach to constify variables if you can. But having said this, this makes more sense in the cases where a variable is either being passed over as an argument or it is shared between different pieces of code (like class variables). The main idea is to stop accidental modification of variables by other code which doesn't know that this variable is not meant to be changed.

Therefore, in light of the above, for variables local to a function, constifying them is a sort of overkill. However, doing this doesn't harm anything.

司马昭之心 2024-10-08 16:14:46

这样做没有任何错误,但是当您知道不应该修改对象时,您可以使用const来让编译器帮助您强制执行约束。如果您不关心对象是否被修改,那么它就是多余的。

There's nothing wrong with doing that, but you use const to enlist the compiler in helping you enforce a constraint, when you know an object shouldn't be modified. If you don't care if the object is modified, than it's superfluous.

谁人与我共长歌 2024-10-08 16:14:46

以我的拙见,您应该抓住一切机会利用强类型语言的编译器。我使用 const 来表示临时变量、局部变量、不可变引用等。

Const Correctness C++ FAQ 可能有更多有用的信息。

In my humble opinion you should take advantage of a strongly-typed language's compiler at every opportunity. I use const for temporary, local variables, immutable references, etc.

The Const Correctness C++ FAQ might have more useful information.

世俗缘 2024-10-08 16:14:45

在局部变量上使用 const 可以提高代码的清晰度,因此这是一个好主意。您看到 const 并且您立即知道该变量在以后的作用域中永远不会更改。它与缩短函数和提前返回属于同一系列。

开发人员很懒——他们常常认为这是一个无用的词,不会改变任何东西。在我看来,他们错了。

Using const on local variables improves code clarity, so it's a good idea. You see const and you immediately know that the variable is never changed later in scope. It's from the same series as making functions short and returning early.

Developers are lazy - they often think that it's a useless word that doesn't change anything. IMO they are wrong.

醉城メ夜风 2024-10-08 16:14:45

这实际上与很少使用断言的原因相同。接口上的 const 是强制的,实现中的 const 是自愿的。程序员都是懒惰的。

编辑:以防万一不清楚,您的方法更好。

This is effectively the same reason why assertions are rarely used. const on interfaces is mandatory, const in the implementation is voluntary. Programmers are lazy.

Edit: just in case it isn't clear, your approach is better.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文