16 April, 2009 § 3 Comments
I just finished reading Effective C++ by Scott Meyers and it is a great book for anybody that works with C++. Many of the hidden and behind-the-scenes workings in C++ are documented in this book. Unlike most programming books, this one is an enjoyable read, one that I read from cover to cover. In the next few days I’ll be posting notes to some of the Items in the book. Here are the first two:
Item 3: Use const whenever possible.
I had been looking for a chapter like this for a long time, but never got around to finding one until now. Using const in your code makes use of your code much more strict and behave in the way that it was intended to. I take pleasure in showing off my use of const-ness in my code, and for some of the lesser known uses I have this Item to thank for. The most confusing use of const is with pointers to data.
char greeting = "hello"; char * const foo = greeting; const char* const bar = greeting;
In the foo example above, only the pointer is const, greeting can be changed to “goodbye” and the compiler will still be happy. In the bar example, both the pointer and the data are const, meaning that neither can change. The latter is usually what people want.
const should also be applied to iterators of STL container types. If you are performing only a read-only operation on a vector, you should use ::const_iterator instead of ::iterator.
Item 5: Know what functions C++ silently writes and calls.
Unless you explicitly declare a copy constructor and an assignment operator, C++ will implicitly generate one for you. If your class only contains integral types like ints, this usually isn’t a big worry, yet if your class contains pointers, you may want to be scared. The default implementations provided by the C++ compiler will generate shallow copies of the object, meaning that you can end up with two objects pointing at the same block of memory.