What is a question that only expert C++ programmers can answer?

Resource Acquisition Is Initialization

Answer by Brian Bi:

We C++ programmers know not to call ourselves experts, because we discover new obscure C++ rules all the time and constantly feel humbled before the language's sheer complexity.

But if I had to ask only one question to assess someone's understanding of C++, I would ask: What is RAII and why is it important? Understanding RAII doesn't make you an expert in C++, but it does mean you understand the foundational principle of resource management in C++, one which sets it apart from other languages. And I would be very suspicious of anyone claiming to have expertise in C++ if they don't understand RAII.

The basic principles (some wording adapted from video below):

  • A resource should have an owner: some kind of handle object. If the handle object has automatic storage duration, it will be cleaned up automatically when it goes out of scope, regardless of whether the scope was left by flowing off the end, returning from a function, or throwing an exception.
  • "Resource Acquisition Is Initialization" (RAII): acquire resources in the constructor and release them in the destructor. This is what ties the lifetime of a resource to its handle's scope, and is therefore absolutely crucial for managing resources in C++.
  • Throw exceptions in case of failure. In particular, throw if a constructor cannot construct an object. If a constructor ends up not throwing, it means the object has been successfully constructed; it now holds a resource and satisfies the class invariants. If the object could not be constructed, you will not see the object at all, since the scope will be exited by an exception.

See Stroustrup's lecture, The Essence of C++. Video:


What is a question that only expert C++ programmers can answer?


Leave a comment

Filed under Life

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s