Coding Standards: Non-const reference parameters in C++ are evil

roger's picture

This is just a minor rant:

In C++, const references are useful for parameters, because they avoid copying the arguments to a method. Non-const references, on the other hand, are pure evil, because there’s no way (at the call site) to immediately see that a method might change a variable:

int expectedVersion = 1;
ValidateVersion(expectedVersion);

By looking at this, you can’t tell that ValidateVersion is declared as void ValidateVersion(int &version) and might actually change the value.

Use a pointer instead:

ValidateVersion(&expectedVersion);

Then, when I’m looking at the call site, I have an expectation that the value might change.

Comments

IN OUT SAL notation usually

IN OUT SAL notation usually helps here

Re: IN OUT SAL notation

No it doesn't, because it lives on the declaration. I can't see what's happening by simply looking at the caller.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.