C++ 告诉我 const 的正确性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/136880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:07:46  来源:igfitidea点击:

Sell me on const correctness

c++const-correctness

提问by Jason Baker

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:

那么为什么总是建议尽可能多地使用 const 呢?在我看来,在 C++ 中使用 const 可能比帮助更痛苦。但话又说回来,我是从 python 的角度来看这个的:如果你不想改变某些东西,就不要改变它。话虽如此,这里有几个问题:

  1. It seems like every time I mark something as const, I get an error and have to change some other function somewhere to be const too. Then this causes me to have to change anotherfunction somewhere else. Is this something that just gets easier with experience?

  2. Are the benefits of using const reallyenough 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?

  1. 似乎每次我将某些内容标记为 const 时,我都会收到一个错误,并且必须在某处更改其他一些函数以使其也为 const。然后这导致我不得不在其他地方更改另一个功能。这是否会随着经验变得更容易?

  2. 使用 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.

我应该注意到,此时此刻,我最关注的是使用 const 来实现正确性和可维护性目的的好处,尽管了解性能影响也很好。

回答by Jordan Parmer

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

这是关于“常量正确性”的权威文章:https: //isocpp.org/wiki/faq/const-correctness

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

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

  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 )
    
  1. 它可以防止您意外更改不打算更改的变量,
  2. 它可以保护您免于进行意外的变量分配,并且
  3. 编译器可以优化它。例如,您可以免受

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

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.

同时,编译器可以生成更高效的代码,因为它始终准确地知道变量/函数的状态。如果您正在编写紧凑的 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-correctness,但最终代码更简洁,更安全。当您进行大量 C++ 开发时,这种好处很快就会显现出来。

回答by Doug T.

Here's a piece of code with a common error that const correctness can protect you against:

这是一段带有常见错误的代码,const 正确性可以保护您免受此错误的影响:

void foo(const int DEFCON)
{
   if (DEFCON = 1)     //< FLAGGED AS COMPILER ERROR! WORLD SAVED!
   {
       fire_missiles();
   }
}

回答by Chris Mayer

It seems like every time I mark something as const, I get an error and have to change some other function somewhere to be const too. Then this causes me to have to change another function somewhere else. Is this something that just gets easier with experience?

似乎每次我将某些内容标记为 const 时,我都会收到一个错误,并且必须在某处更改其他一些函数以使其也为 const。然后这导致我不得不在其他地方更改另一个功能。这是否会随着经验变得更容易?

From experience, this is a total myth. It happens when non const-correct sits with const-correct code, sure. If you design const-correct from the start, this should NEVER be an issue. If you make something const, and then something else doesn't complile, the compiler is telling you something extremely important, and you should take the time to fix it properly.

根据经验,这完全是一个神话。当然,当非常量正确的代码与常量正确的代码在一起时,就会发生这种情况。如果您从一开始就设计了 const-correct,这应该永远不会成为问题。如果你做了一些 const,然后其他的东西不编译,编译器告诉你一些非常重要的事情,你应该花时间正确修复它。

回答by Antonio Haley

It's not for you when you are writing the code initially. It's for someone else (or you a few months later) who is looking at the method declaration inside the class or interface to see what it does. Not modifying an object is a significant piece of information to glean from that.

当您最初编写代码时,它不适合您。这是给正在查看类或接口中的方法声明以了解其作用的其他人(或几个月后的您)。不修改对象是从中收集的重要信息。

回答by QBziZ

If you use const rigorously, you'd be surprised how few real variables there are in most functions. Often no more than a loop counter. If your code is reaching that point, you get a warm feeling inside...validation by compilation...the realm of functional programming is nearby...you can almost touch it now...

如果您严格使用 const,您会惊讶于大多数函数中的实际变量如此之少。通常只是一个循环计数器。如果你的代码达到了那个点,你会在里面感受到一种温暖的感觉......通过编译验证......函数式编程的领域就在附近......你现在几乎可以接触它......

回答by JohnMcG

const is a promise your are making as a developer, and enlisting the compiler's help in enforcing.

const 是您作为开发人员做出的承诺,并争取编译器的帮助来执行。

My reasons for being const-correct:

我的常量正确的原因:

  • It communicates to clients of your function that your will not change the variable or object
  • Accepting arguments by const reference gives you the efficiency of passing by reference with the safety of passing by value.
  • Writing your interfaces as const correct will enable clients to use them. If you write your interface to take in non-const references, clients who are using const will need to cast constness away in order to work with you. This is especially annoying if your interface accepts non-const char*'s, and your clients are using std::strings, since you can only get a const char* from them.
  • Using const will enlist the compiler in keeping you honest so you don't mistakenly change something that shouldn't change.
  • 它向您的函数的客户端传达您不会更改变量或对象
  • 通过 const 引用接受参数为您提供了通过引用传递的效率以及通过值传递的安全性。
  • 将您的接口编写为 const 正确将使客户端能够使用它们。如果您编写接口以接收非常量引用,则使用 const 的客户将需要抛弃 constness 才能与您一起工作。如果您的接口接受非常量 char* 并且您的客户端使用 std::strings,这尤其令人讨厌,因为您只能从它们获取 const char*。
  • 使用 const 将使编译器让您保持诚实,这样您就不会错误地更改不应更改的内容。

回答by andreas buykx

Programming C++ without const is like driving without the safety belt on.

没有 const 的 C++ 编程就像没有系安全带开车一样。

It's a pain to put the safety belt on each time you step in the car, and 364 out of 365 days you'll arrive safely.

每次上车都系上安全带很痛苦,365 天中的 364 天你都会安全到达。

The only difference is that when you get in trouble with your car you'll feel it immediately, whereas with programming without const you may have to search for two weeks what caused that crash only to find out that you inadvertently messed up a function argument that you passed by non-const reference for efficiency.

唯一的区别是,当您的汽车遇到麻烦时,您会立即感觉到,而在没有 const 的编程中,您可能需要搜索两周的时间才能发现导致崩溃的原因,结果却发现您无意中弄乱了一个函数参数您通过非常量引用传递了效率。

回答by Pat Notz

My philosophy is that if you're going to use a nit-picky language with compile time checks than make the best use of it you can. constis a compiler enforced way of communicating what you mean... it's better than comments or doxygen will ever be. You're paying the price, why not derive the value?

我的理念是,如果您要使用带有编译时检查的挑剔语言,那么您可以最好地利用它。 const是一种编译器强制执行的传达您的意思的方式……它比评论或 doxygen 更好。你付出了代价,为什么不推导出价值?

回答by bk1e

For embedded programming, using constjudiciously when declaring global data structures can save a lot of RAM by causing the constant data to be located in ROM or flash without copying to RAM at boot time.

对于嵌入式编程,const在声明全局数据结构时明智地使用可以通过使常量数据位于 ROM 或闪存中而不在启动时复制到 RAM 来节省大量 RAM。

In everyday programming, using constcarefully helps you avoid writing programs that crash or behave unpredictably because they attempt to modify string literals and other constant global data.

在日常编程中,const小心使用可以帮助您避免编写由于尝试修改字符串文字和其他常量全局数据而导致崩溃或行为不可预测的程序。

When working with other programmers on large projects, using constproperly helps prevent the other programmers from throttling you.

在大型项目中与其他程序员一起工作时,const正确使用有助于防止其他程序员限制您。

回答by Peter Kovacs

const correctness is one of those things that really needs to be in place from the beginning. As you've found, its a big pain to add it on later, especially when there is a lot of dependency between the new functions you are adding and old non-const-correct functions that already exist.

const 正确性是真正需要从一开始就做好的事情之一。正如您所发现的,以后添加它是一件很痛苦的事情,尤其是当您添加的新函数与已经存在的旧的非常量正确的函数之间存在大量依赖时。

In a lot of the code that I write, its really been worth the effort because we tend to use composition a lot:

在我编写的许多代码中,它确实值得付出努力,因为我们经常使用组合:

class A { ... }
class B { A m_a; const A& getA() const { return m_a; } };

If we did not have const-correctness, then you would have to resort to returning complex objects by value in order to assure yourself that nobody was manipulating class B's internal state behind your back.

如果我们没有常量正确性,那么您将不得不求助于按值返回复杂对象,以确保没有人在背后操纵 B 类的内部状态。

In short, const-correctness is a defensive programming mechanism to save yourself from pain down the road.

简而言之,const-correctness 是一种防御性编程机制,可以让您免于痛苦。