Probably Dance

I can program and like games

Month: October, 2014

Comma Operator RAII Abuse

Here’s a neat little trick that one of my co-workers, Clint Levijoki, discovered. In C++ you often use an RAII wrapper that you place on the stack if you want to be sure that code gets run at a later point. One good example would be std::lock_guard which you use if you want to be sure that a lock gets released in the future, or scoped profiling which you use to stop a timer in the future. For example for this:

std::string foo();
void bar()
{
    std::string baz = foo();
    // do something with baz
}

If you want to profile foo() you’d write it like this:

std::string foo();
void bar()
{
    std::string baz;
    {
        ScopedProfiler profile_foo("foo()");
        baz = foo();
    }
    // do something with baz
}

Which is less pretty and slightly slower. Alternatively you can use the comma operator and do it like this:

std::string foo();
void bar()
{
    std::string baz = (ScopedProfiler("foo()"), foo());
    // do something with baz
}

And this will start a timer before calling foo(), and stop the timer after calling foo(). You could wrap it in a macro to make it more readable. And the benefit is obviously that you don’t have to destroy your function flow when you want to insert RAII objects.

Read the rest of this entry »

Another Opinion on “Almost Always Auto”

Herb Sutter has been promoting his almost always auto style again, and I think it is harmful. I would agree with “almost always auto” in Scala. I disagree with it in C++. And that’s because there is a slight difference in syntax for type inference between the two languages.

Here’s type deduction in Scala:

val inferred = 0
val typed : Int = 1

And here it is in C++

auto inferred = 0;
int typed = 1;

Seems similar, right? But the difference in syntax leads to different long term programmer behavior.

Read the rest of this entry »