Saturday, April 21, 2007

No Style Is Perfect.... a case for passing args by reference in C++

Let's say you have a style guide that says: "Never pass parameters by reference in C++ unless it's const"

Sounds fair, isn't it? After all, passing by reference is indeed fairly confusing concept. You see a variable like a local variable, but you can assign to it. Is it a good policy? Maybe. But lets see...

Assume you have a function like:

void DoStuff(Crap* crap) { ... }

You want "crap" to be mutable, so you cannot pass it as (Crap& crap) according to the policy. You have to pass a pointer.

Then in the main() you get a code like this:

main(...)
{
...
Crap crap;
DoStuff(&crap);
...
}

Now, guess what do you get in DoStuff after a bunch of junior developers changed it? Something like:

void DoStuff(Crap* crap) {
...
crap = new different pointer....
use crap
...
}

Crap...

No really, I just fixed the one like that. Not good. Crap. Keep an eye on things like that.

No comments:

Post a Comment