Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does const correctness help write better programs?

This question is from a C# guy asking the C++ people. (I know a fair bit of C but only have some general knowledge of C++).

Allot of C++ developers that come to C# say they miss const correctness, which seems rather strange to me. In .Net in order to disallow changing of things you need to create immutable objects or objects with read only properties/fields, or to pass copies of objects (by default structs are copied).

Is C++ const correctness, a mechanism to create immutable/readonly objects, or is there more to it? If the purpose is to create immutable/readonly objects, the same thing can be done in an environment like .Net.

like image 659
Pop Catalin Avatar asked Mar 20 '26 04:03

Pop Catalin


2 Answers

A whole section is devoted to Const Correctness in the FAQ. Enjoy!

like image 84
dirkgently Avatar answered Mar 21 '26 16:03

dirkgently


const correctness in C++ is at heart simply a way of saying exactly what you mean:

void foo( const sometype & t ) {
   ...
}

says "I will not change the object referred to by t, and if I try to, please Mr. Compiler warn me about it".

It is not a security feature or a way of (reliably) creating read-only objects, because it is trivial to subvert using C-style casts.