Hate UML?

Draw sequence diagrams in seconds.
http://www.websequencediagrams.com

Rules for Effective C++
Posted on: 2007-04-06 10:25:28
I used to be a strong supporter of C++. It was the perfect language. In C++, if you want to influence how the hardware instructions are generated, you can do that. If you want to program without pointers and without caring about how memory is allocated, you can do that.

Recently, however, my views have changed after reading Scott Meyer's book, Effective C++. In Meyer's book, he goes through every feature of C++ and shows you how you have to program with extreme care to avoid undefined behaviour. It seems like every modern feature that C++ has was specifically designed to help you shoot yourself in the foot.

I never realized this before, because I simply never use these dangerous features. In this article, I'll show you how to program in C++ safely.

C++'s Broken Exceptions

Take exceptions, for example. Many programmers will tell you that they are a great idea. They let you indicate errors when creating object, and avoid making you check return codes. You can handle errors in the areas of the code that is prepared to handle them.

What you may not know is that using exceptions in C++ makes a lot of code unsafe. In effect, it means that you cannot use pointers. Take this code, for example:

void foo()
{
    MyObject* obj = new MyObject();

    bar();

    delete obj;    
}

If you are a C++ programmer and you use exceptions, you should see the obvious memory leak. If bar() throws an exception, or calls any function that throws an exception, then obj will not be deleted.

Steve's rules for effective C++

I have been programming in C++ for a decade, and I never realized these flaws until I read Meyer's books. I find C++ to be just fine, and the reason for that is because I program in a style that doesn't involve these pitfals. Here's how you can program in this way too:

Avoid exceptions

Exceptions will only leave you open to the memory and resource leaks. Don't use them. The exception to this rule is if you are programming in a style that doesn't use pointers, and everything is encapsulated into smart pointers.

Constructors should do nothing

Constructors have no way of returning an error code (unless you use exceptions, which are bad). That means that your constructors shouldn't do any real work. Don't try to open up a database connection, or call any functions that could fail. Constructors should be used only to initialize data members.

Use copy constructors sparingly

Copy constructors are very error prone, because they are another thing that you have to remember to change if you add a data member. You're much better off if you don't allow copying at all. Just pass pointers around. If you must pass by value, then don't put anything in your object, like pointers, that will require special handling. That way, you can use the automatically generated copy constructor. Unlike you, the compiler will never forget anything.

Use malloc or new without checking the result

I used to write programs that checked every call to malloc() and new() for failure. In Microsoft C++, the new() operator will actually through an exception if it fails, so checking for NULL is useless anyway. Today's machines have gigabyes of memory, and you don't need to verify every call to malloc() or new().

It's actually quite hard to induce these functions to fail, so even if you did handle their failure, you probably wouldn't test it. Do you really want to be releasing code that you haven't tested? There are cases where it would be better for your program to crash, then to continue to operate in an undefined state.

However, there are times where I would check whether a memory allocation failed:

  • When you are allocating something that is several megabytes, like space for images or files. In this case, it is quite possible for the allocation to fail if the user has opened up too many files in your program.
  • When you are programming for a nuclear reactor, or space shuttle. Also, a missile guidance system would be acceptable.
When you are programming for an embedded device, however, it might be beneficial to not check the return code of malloc. This is when there should be enough memory in the heap for all operations. If your process silently fails when memory allocation fails, you might never catch a memory leak that is exhausting your heap. It is much better to fail catastrophically by trying to use the NULL pointer than silently failing.

Want more programming tech talk?
Add to Circles on Google Plus
Subscribe to posts

Post comment

Real Name:
Your Email (Not displayed):

Text only. No HTML. If you write "http:" your message will be ignored.
Choose an edit password if you want to be able to edit or delete your comment later.
Editing Password (Optional):

Pete from G32 Technologies

2007-08-15 03:02:26
Steve, couldn't agree more with your rules. I think I might have been the same Effective C++ book and have come to the same conclusions before reading it. It's a pity that more companies don't place greater emphasis on writing bug free C++. My experience is that an encyclopaedic knowledge of the standard text books is preferred.

Dan

2009-01-02 15:25:39
Exceptions without RAII are bad. Code without RAII is worse. This is a naive argument against eexceptions.

Yang

2009-06-25 04:37:17
Learn about RAII.

Anonynous Cowardon

2009-06-30 21:07:15
RAII is the answer. Boost is your friend.

Marc Lepage

2011-03-25 11:30:01
I've programmed a lot of C++ and read all Meyers books (and reviewed most of them for Slashdot).

Others are right, use RAII (e.g. smart pointers) and your problems with exceptions will go away.

Copy constructors are handy in many cases. For example, in multithreaded programming (or simply for security) is it often better to take a copy than to coordinate access to the identical object. There are ways to write classes so that the copy constructor shares code with the other constructor, reducing the risk of not keeping them in sync.

IIRC correctly, in Standard C++ you can configure whether new throws or not. Also, IIRC, it's hard to get Visual C++ to obey this. Regardless, an additional reason to avoid the checks everywhere is to avoid code bloat. Relying on exceptions in this case is a good idea.

I still like C++, because it's a powerful and expressive language for building complicated and performant systems. I'm not saying you should write simple programs in C++, but when you're doing data mining suites or geospatial processing, C++'s facilities for abstraction are quite handy. Also templates have their uses (when not abused).

D

2012-12-19 12:38:40
(I know the post is 5 years old, but I'll reply anyway)

I think there are critical problems with your proposed plan to not use exceptions. The post even contains the problem:

"Don't use exceptions [....] In Microsoft C++, the new() operator will actually throw an exception if it fails"

(Are you suggesting programming in C++ without using new?)

Email
steve.hanov@gmail.com

Other posts by Steve

Yes, You Absolutely Might Possibly Need an EIN to Sell Software to the US How Asana Breaks the Rules About Per-Seat Pricing 5 Ways PowToon Made Me Want to Buy Their Software How I run my business selling software to Americans 0, 1, Many, a Zillion Give your Commodore 64 new life with an SD card reader 20 lines of code that will beat A/B testing every time [comic] Appreciation of xkcd comics vs. technical ability VP trees: A data structure for finding stuff fast Why you should go to the Business of Software Conference Next Year Four ways of handling asynchronous operations in node.js Type-checked CoffeeScript with jzbuild Zero load time file formats Finding the top K items in a list efficiently An instant rhyming dictionary for any web site Succinct Data Structures: Cramming 80,000 words into a Javascript file. Throw away the keys: Easy, Minimal Perfect Hashing Why don't web browsers do this? Fun with Colour Difference Compressing dictionaries with a DAWG Fast and Easy Levenshtein distance using a Trie The Curious Complexity of Being Turned On Cross-domain communication the HTML5 way Five essential steps to prepare for your next programming interview Minimal usable Ubuntu with one command Finding awesome developers in programming interviews Compress your JSON with automatic type extraction JZBUILD - An Easy Javascript Build System Pssst! Want to stream your videos to your iPod? "This is stupid. Your program doesn't work," my wife told me The simple and obvious way to walk through a graph Asking users for steps to reproduce bugs, and other dumb ideas Creating portable binaries on Linux Bending over: How to sell your software to large companies Regular Expression Matching can be Ugly and Slow C++: A language for next generation web apps qb.js: An implementation of QBASIC in Javascript Zwibbler: A simple drawing program using Javascript and Canvas You don't need a project/solution to use the VC++ debugger Boring Date (comic) barcamp (comic) How IE <canvas> tag emulation works I didn't know you could mix and match (comic) Sign here (comic) It's a dirty job... (comic) The PenIsland Problem: Text-to-speech for domain names Pitching to VCs #2 (comic) Building a better rhyming dictionary Does Android team with eccentric geeks? (comic) Comment spam defeated at last Pitching to VCs (comic) How QBASIC almost got me killed Blame the extensions (comic) How to run a linux based home web server Microsoft's generosity knows no end for a year (comic) Using the Acer Aspire One as a web server When programmers design web sites (comic) Finding great ideas for your startup Game Theory, Salary Negotiation, and Programmers Coding tips they don't teach you in school When a reporter mangles your elevator pitch Test Driven Development without Tears Drawing Graphs with Physics Free up disk space in Ubuntu Keeping Abreast of Pornographic Research in Computer Science Exploiting perceptual colour difference for edge detection Experiment: Deleting a post from the Internet Is 2009 the year of Linux malware? Email Etiquette How a programmer reads your resume (comic) How wide should you make your web page? Usability Nightmare: Xfce Settings Manager cairo blur image surface Automatically remove wordiness from your writing Why Perforce is more scalable than Git Optimizing Ubuntu to run from a USB key or SD card UMA Questions Answered Make Windows XP look like Ubuntu, with Spinning Cube Effect See sound without drugs Standby Preventer Stock Picking using Python Spoke.com scam Stackoverflow.com Copy a cairo surface to the windows clipboard Simulating freehand drawing with Cairo Free, Raw Stock Data Installing Ubuntu on the Via Artigo Why are all my lines fuzzy in cairo? A simple command line calculator Tool for Creating UML Sequence Diagrams Exploring sound with Wavelets UMA and free long distance UMA's dirty secrets Installing the Latest Debian on an Ancient Laptop Dissecting Adsense HTML/ Javascript/ CSS Pretty Printer Web Comic Aggregator Experiments in making money online How much cash do celebrities make? Draw waveforms and hear them Cell Phones on Airplanes Detecting C++ memory leaks What does your phone number spell? A Rhyming Engine Rules for Effective C++ Cell Phone Secrets