Unknown's avatar

C++ Wish List: Constify

Sometimes you want to mutate a value for a little while, and then freeze it. Reasons include:

– Interfacing with an API that likes to mutate its arguments
– Doing an in-place algorithm such as sorting
– It’s just easier to express the algorithm that way

But this kind of error occurs:

	void fill_array(float *values, int length);

	float *to_be_mutated = new float[42];
	float *to_be_sorted = new float[42];

	fill_array(to_be_mutated);
	sort_array(to_be_mutated); // oh no! should have passed to_be_sorted!

These kind of errors are pretty common in my experience, especially if variables with compatible types are similarly named.

Wouldn’t it be cool if you could tell the C++ compiler to convert a local variable into a const variable for the remainder of the function?

	void fill_array(float *values, int length);

	float *to_be_mutated = new float[42];
	float *to_be_sorted = new float[42];

	fill_array(to_be_mutated);
	constify to_be_mutated;

	sort_array(to_be_mutated); // compile error!

I don’t know much about compilers, but this seems like it would be easy to implement.