Monday, 30 November 2009

Const in arguments.

Keyword const is used in arguments to both make the code more readable, and faster. You normally use const& to show that you want access to a large thing, but don't want it on the stack (that would be nasty and big copy constructor stuff). However, some people think that const means that something won't be changed...

Okay, const is used to define that the code about to be using it in its const form wont change it. It's not a declaration that the value won't change.


int Foo( int &out, const int &in1, const int &in2 )
out = 0;
if( in1 > 0 )
out += in1;
out += in2;

This code initialises the output variable and then adds in1 if it's positive, and in2 regardless.

Does it do what's expected in the following code?

int a = 1;
int b = 2;
int c = 5;

Foo( a, b, c );
// a now equals 7

yes, it does. Now how about this?

int a = 2;
int b = 5;

Foo( a, a, b );
// a now equals 5!?

Also, what is a if you call Foo(a,a,a) ? ZERO!

Remember, const doesn't safeguard you against change from the outside. it protects you against change from things you call, not things you're called from. Even then it doesn't actually safeguard completely as it's perfectly valid code to do a const_cast<>().

Have a look at any 3d math library's implementation of a "matrix * matrix". Unless they do all their work in registers, they will generally check to see if the output matrix is the same pointer as the input matrices and asserts on it.
Post a Comment