Sell โ€‹โ€‹me on const const

So why exactly did he always recommend using const as often as possible? It seems to me that using const can be more painful than using C ++. But then again, I come to this from the point of view of python: if you do not want something to change, do not change it. So, with that said, here are a few questions:

  • It seems that every time I mark something as const, I get an error message and must change some other function to be const. Then it makes me change another function elsewhere. Is it something that just gets easier with experience?

  • Are the benefits of using const really sufficient to compensate for the problem? If you are not going to change the object, why not just write code that will not change it?

I should note that at the moment I am most focused on the benefits of using const for correctness and ease of maintenance, although it is also nice to have an idea of โ€‹โ€‹the performance implications.

+84
c ++
Sep 25 '08 at 23:34
source share
17 answers

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

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

  • It protects you from accidentally changing variables that are not meant to be changed,
  • It protects you from random variable assignments and
  • The compiler can optimize it. For example, you are protected from

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

At the same time, the compiler can generate more efficient code, since it knows exactly what state of the variable / function will always be. If you write hard code in C ++, thatโ€™s good.

You are right that it can be difficult to use the constant-regularity consistently, but the final code is more concise and safe for programming. When you do a lot of development in C ++, the benefits of this quickly come to light.

+121
Sep 25 '08 at 23:40
source share

Here's a piece of code with a common error that is correct for const, can protect you from:

 void foo(const int DEFCON) { if (DEFCON = 1) //< FLAGGED AS COMPILER ERROR! WORLD SAVED! { fire_missiles(); } } 
+108
Sep 25 '08 at 23:37
source share

It seems that every time I mark something as const, I get an error message and should change another function somewhere there will also be const. Then it makes me change another function elsewhere. Is that what becomes easier with experience?

From experience, this is a complete myth. This happens when it is not const-sitting correctly with constant code, of course. If you are designing const-correct from the start, this should NEVER be a problem. If you create something const, and then something else does not complicate, the compiler tells you something extremely important, and you must take the time to fix it correctly .

+49
Sep 26 '08 at 0:19
source share

This is not for you when you write code first. This is for someone else (or you in a few months) who is looking at a method declaration inside a class or interface to see what it does. Do not modify the object - this is a significant part of the information that can be extracted from this.

+24
Sep 25 '08 at 23:37
source share

const is a promise you make as a developer, and the help of the compiler to enforce compliance.

My reasons for const-correct:

  • It contacts clients of your function that you will not change a variable or object
  • Taking arguments with a const reference gives you the efficiency of passing by reference with the security of passing by value.
  • Writing your interfaces as const correctly will allow clients to use them. If you write your interface for use in non-constant links, clients that use a constant will need to specify a constant in order to work with you. This is especially annoying if your interface accepts non-const char * and your clients use std :: strings, since you can only get const char * from them.
  • Using const will require a compiler so that you are honest, so make no mistake, change what shouldn't change.
+20
Sep 26 '08 at 2:24
source share

If you use const strictly, you will be surprised at how few real variables there are in most functions. Often nothing more than a cycle counter. If your code reaches this point, you get a warm feeling inside ... validation by compilation ... the area of โ€‹โ€‹functional programming is nearby ... you can almost touch it now ...

+19
Sep 27 '08 at 0:03
source share

C ++ programming without const is like driving without a seat belt.

It is a pain to put a seat belt every time you enter the car, and 364 out of 365 days you will arrive safely.

The only difference is that when you have problems with the car, you will immediately feel it, while when programming without const, you may need to find two weeks, which caused this crash, only to find out that you accidentally mixed up the function argument, which you passed using a non-constant link for efficiency.

+16
Sep 26 '08 at 8:00
source share

My philosophy is that if you are going to use a nit-picky language with compile-time checking than you can use it in the best way you can. const is a forced way to compile to convey what you mean ... it's better than comments or doxygen ever. You pay the price, why not get the value?

+14
Sep 26 '08 at 0:54
source share

For built-in programming, using const reasonable when declaring global data structures can save a lot of RAM by forcing persistent data to be located in ROM or blinking without copying to RAM at boot time.

In everyday programming, using const will help you avoid writing programs that cause unpredictable crashes or behave unpredictably because they try to modify string literals and other persistent global data.

When working with other programmers in large projects, using const correctly helps prevent other programmers from throttling.

+12
Sep 26 '08 at 3:30
source share

const helps you isolate code that "changes things" behind your back. So, in the class you will mark all methods that will not change the state of the object as const . This means that const instances of this class will no longer be able to call any non- const methods. Thus, you cannot accidentally call functionality that can change your object.

In addition, const is part of the overload mechanism, so you can have two methods with the same signatures, but one with const and one without it. The one with const is called for const links, and the other for links << 20>.

Example:

 #include <iostream> class HelloWorld { bool hw_called; public: HelloWorld() : hw_called(false) {} void hw() const { std::cout << "Hello, world! (const)\n"; // hw_called = true; <-- not allowed } void hw() { std::cout << "Hello, world! (non-const)\n"; hw_called = true; } }; int main() { HelloWorld hw; HelloWorld* phw1(&hw); HelloWorld const* phw2(&hw); hw.hw(); // calls non-const version phw1->hw(); // calls non-const version phw2->hw(); // calls const version return 0; } 
+11
Sep 25 '08 at 23:45
source share

const is one of those things that really should be in place from the start. As you discovered, its a big pain to add it later, especially when there is a lot of dependency between the new functions that you add and the old non-constant functions that already exist.

In the large amount of code that I write, it was really 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, you would have to resort to returning complex objects at a cost to make sure that no one was manipulating the internal state of class B. Behind you.

In short, const-correctness is a protective programming mechanism to save you from pain along the way.

+8
Dec 09 '09 at 2:40
source share

Say you have a variable in Python. You know that you should not change it. What if you accidentally do?

C ++ gives you the ability to protect yourself from accidentally doing what you shouldn't have done in the first place. Technically, you can get around this anyway, but you need to add extra work to shoot yourself.

+5
Sep 26 '08 at 3:46
source share

There is a good article here about const in C ++. This is a pretty direct opinion, but I hope this helps some.

+4
Sep 25 '08 at 23:37
source share

When you use the const keyword, you are specifying a different interface for your classes. There is an interface that includes all methods and an interface that includes only const methods. Obviously, this allows you to restrict access to certain things that you do not want to change.

Yes, it gets easier over time.

+2
Sep 26 '08 at 0:07
source share

I like constant correctness ... in theory. Every time I tried to put it into practice, it eventually broke, and const_cast starts crawling, making the code ugly.

Maybe it's just the design patterns that I use, but const always turns out to be too wide a brush.

For example, imagine a simple database engine ... it has schema objects, tables, fields, etc. A user may have a const table pointer, meaning they are not allowed to modify the table schema directly ... but what about manipulating the data associated with the table? If the Insert () method is marked as const, then it must discard the constant in order to actually manipulate the database. If it is not marked as const, it does not protect against calling the AddField method.

Perhaps the answer is to split the class based on constant requirements, but this tends to complicate the design more than I would like for the benefit it brings.

+1
Sep 26 '08 at 0:01
source share

You can also give compiler hints with a constant ... according to the following code

 #include <string> void f(const std::string& s) { } void x( std::string& x) { } void main() { f("blah"); x("blah"); // won't compile... } 
+1
Sep 26 '08 at 3:59
source share

Also, without const correction, you cannot pass arguments using the const reference, which can lead to more copies. Passing on a (non-const) link is not a solution, since non const links cannot be tied to temporary ones.

+1
Jan 13 '16 at 15:13
source share