Warning, /multimedia/amarok/HACKING/const_correctness.txt is written in an unsupported language. File is not indexed.

0001 === Const Correctness ===
0002 
0003 What is const correctness?
0004 
0005 It's a programming paradigm that helps writing correct code. In C++, const
0006 correctness comprises a set of different techniques, you can read up about them
0007 here [1]. In this article however I only want to focus on one form of const
0008 correctness, that is object constness.
0009 
0010 Why should I care about const correctness?
0011 
0012 Because it increases type safety, makes your code more easy to understand, and
0013 it helps making your code correct.
0014 
0015 Let's have an example, the following function:
0016 
0017 void printStruct( MyStruct* str );
0018 
0019 Is it save to assume that MyStruct is unchanged? Can I give it a structure
0020 that is allocated in a read-only memory location?
0021 We can assume this (because of the name of the function) but we can't be sure.
0022 
0023 It get's even worse if you use a reference like this:
0024 
0025 void printStruct( MyStruct& str );
0026 
0027 Now you can't even see in the calling code that something might go wrong since
0028 a line like this:
0029 
0030 printStruct( str );
0031 
0032 is not seen as dangerous. In C it is always a call-by-value. In C++ it isn't.
0033 
0034 The solution is easy. Just declare the function like this:
0035 
0036 void printStruct( const MyStruct& str );
0037 
0038 Now nothing can go wrong. We get the benefit of a call-by-reference without
0039 the danger.
0040 Now one last problem. What if MyStruct is a class like this:
0041 
0042 class MyStruct {
0043   void print();
0044 }
0045 
0046 How would the compiler know that calling "print" on the const MyStruct does
0047 not change the object?
0048 The compiler can't. We have to tell it like this:
0049 
0050   void print() const;
0051 
0052 Now everything is all right. Everybody is on the same page and we don't
0053 have to look an hour which function might have changed our variables
0054 in some unexpected place.
0055 
0056 
0057 A last word about payoff.
0058 Regardless if we are just programming for fun or professionally we should
0059 think about payoff.
0060 
0061 Writing "const" all over the place is confusing, costs time and leads
0062 to compile time errors.
0063 So why the effort?
0064 This does not really prevent many bugs. At least in my experience.
0065 However it has one big benefit: It really helps searching bugs. Const-
0066 correctness is really a nice thing since we are using more time searching
0067 bugs than actually programming.
0068 
0069 [1] http://www.parashift.com/c++-faq-lite/const-correctness.html