More notes on “Effective C++”

17 April, 2009 § 1 Comment

This is a continuation of a previous post that I started after I finished reading Effective C++ by Scott Meyers.

Item 6: Explicitly disallow the use of compiler-generated functions you do not want.
The recommended way of disallowing the use of compiler-generated functions is to privately declare the copy constructor and assignment operator without providing a definition of them. Omaha, aka Google Update, uses this pattern within their code base by using a macro called DISALLOW_EVIL_CONSTRUCTORS. The macro is called from private visibility.

Item 13: Use objects to manage resources.
Well written code that uses objects to manage resources should not have a single use of the operator delete. Classes like auto_ptr and boost::shared_ptr allow for single ownership of pointers and reference-counted pointers, respectively. Both of these classes will call delete on the contained pointer when it goes out of scope. This is perfect if you are worried about exceptional cases and want to make sure you don’t leak memory.

Item 18: Make interfaces easy to use correctly and hard to use incorrectly.
Enumerated types have an inherent problem associated with them. If you declare an enumerated type, you are not limiting your callers to use only the values within the enumerated type. Take a look at the code sample below:

enum eDayOfWeek { Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
void PrintDayOfWeek( eDayOfWeek eDay );
... //function defintion elided
PrintDayOfWeek( (eDayOfWeek) 75 ); //unexpected behavior here

The way that Meyers handles this is by privately declaring the constructor and publicly declaring static methods that return objects, thus protecting against invalid uses of enumerated types. How does this look:

void PrintDayOfWeek( Day day );
... //function definition elided
PrintDayOfWeek( Day::Monday() );

Where Am I?

You are currently browsing entries tagged with google update at JAWS.

Follow

Get every new post delivered to your Inbox.

Join 1,004 other followers