Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concerning RAII: How to prevent errors caused by accidentally creating a temporary?

Tags:

c++

A while age a colleague told me he spent lot of time debugging a race condition. The culprit turned out to be something like this:

void foo()
{
    ScopedLock(this->mutex); // Oops, should have been a named object.
                             // Edit: added the "this->" to fix compilation issue.
    // ....
}

In order to prevent situation from happening again he created the following macro after the definition of the ScopedLock class:

#define ScopedLock(...) Error_You_should_create_a_named_object;

This patch works fine.

Does anyone know any other interesting techniques to prevent this problem?

like image 314
StackedCrooked Avatar asked Mar 01 '11 18:03

StackedCrooked


2 Answers

You should use a static code analyser such as Cppcheck. For the following code:

class a { };

void f() {
    a();
}

cppcheck generates the following output:

$ cppcheck test.cpp
Checking test.cpp...
[test.cpp:4]: (error) instance of "a" object destroyed immediately

There are a wide variety of other common coding errors also detected.

(I'm a fairly new contributor to Cppcheck. I found it a couple of months ago and it's been fantastic working with it.)

like image 112
Greg Hewgill Avatar answered Oct 19 '22 05:10

Greg Hewgill


If you're going to define a macro, I'd probably rather define this one:

#define GET_SCOPED_LOCK(name, mtx) ScopedLock name(mtx)

and stop creating objects other than via the macro.

Then rename ScopedLock to ThisClassNameShouldNotAppearInUserCode if that helps.

like image 41
Steve Jessop Avatar answered Oct 19 '22 04:10

Steve Jessop