Sunday, October 12, 2008

C++ FAQ Lite

http://www.parashift.com/c++-faq-lite/

[18] Const correctness

Constness means using the keyword const to prevent const objects from getting mutated. Declaring the const-ness of a parameter is just another form of type safety.

For example, if you wanted to create a function f() that accepted a std::string, plus you want to promise callers not to change the caller's std::string that gets passed to f(), you can have f() receive its std::string parameter...

  • void f1(const std::string& s);     // Pass by reference-to-const
  • void f2(const std::string* sptr);  // Pass by pointer-to-const
  • void f3(std::string s);            // Pass by value

You have to read pointer declarations right-to-left.

  • const Fred* p means "p points to a Fred that is const" — that is, the Fred object can't be changed via p.
  • Fred* const p means "p is a const pointer to a Fred" — that is, you can change the Fred object via p, but you can't change the pointer p itself.
  • const Fred* const p means "p is a const pointer to a const Fred" — that is, you can't change the pointer p itself, nor can you change the Fred object via p.
"const member function" inspects (rather than mutates) its object.
"const-overloading"

class Fred { ... };
class MyFredList {
public:
   const Fred& operator[] (unsigned index) const; 
subscript operators often come in pairs
   Fred&       operator[] (unsigned index);       
subscript operators often come in pairs
      ...
};