卖我对const正确性 [英] Sell me on const correctness

查看:146
本文介绍了卖我对const正确性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

那么为什么它总是建议尽可能经常使用const?在我看来,使用const可能比C ++中的帮助更痛苦。但是再次,我从python的角度来看:如果你不想改变某些东西,不要改变它。所以这样说,这里有几个问题:

So why exactly is it that it's always recommended to use const as often as possible? It seems to me that using const can be more of a pain than a help in C++. But then again, I'm coming at this from the python perspective: if you don't want something to be changed, don't change it. So with that said, here are a few questions:


  1. 看起来像每次我标记为const,错误和必须改变一些其他函数在某处const。然后这使我不得不改变另一个另一个函数。

使用const 真的的好处足以弥补这个麻烦吗?如果你不打算改变对象,为什么不写代码不改变它?

Are the benefits of using const really enough to compensate for the trouble? If you don't intend on changing an object, why not just not write code that doesn't change it?

我应该注意到,在这个时间点,我最关注的是使用const的正确性和可维护性的目的的好处,虽然它也很高兴对性能的影响。

I should note that at this point in time, I'm most focused on the benefits of using const for correctness and maintainability purposes, although it is also nice to have an idea of the performance implications.

EDIT :我被告知正确的术语是const正确性,这就是现在的标题。

EDIT: I'm told that the correct term is const correctness, so that's what the title is now.

推荐答案

这是关于const correctness的最终文章: https:// isocpp。 org / wiki / faq / const-correctness

This is the definitive article on "const correctness": https://isocpp.org/wiki/faq/const-correctness.

简而言之,使用const是好的做法,因为...

In a nutshell, using const is good practice because...


  1. 它可以防止意外更改不打算更改的变量,

  2. 它可防止意外变量分配,

  3. 编译器可以优化它。例如,您受保护不受

  1. It protects you from accidentally changing variables that aren't intended be changed,
  2. It protects you from making accidental variable assignments, and
  3. The compiler can optimize it. For instance, you are protected from

if( x = y ) // whoops, meant if( x == y )


高效的代码,因为它知道什么是变量/函数的状态在任何时候。如果你正在编写紧凑的C ++代码,这是好的。

At the same time, the compiler can generate more efficient code because it knows exactly what the state of the variable/function will be at all times. If you are writing tight C++ code, this is good.

你是正确的,因为可能难以一致地使用const正确性,但是结束代码更简洁和更安全的程序。当你做很多C ++开发时,这个好处很快就会显现出来。

You are correct in that it can be difficult to use const-correctness consistently, but the end code is more concise and safer to program with. When you do a lot of C++ development, the benefits of this quickly manifest.

这篇关于卖我对const正确性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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