passing POD by value with const qualifiers. Silly or not?

Friedrich W. H. Kossebau kossebau at kde.org
Sat Feb 23 09:48:06 GMT 2008


Am Freitag, 22. Februar 2008, um 21:26 Uhr, schrieb Stefan Teleman:
> On Fri, Feb 22, 2008 at 3:16 PM, Ariya Hidayat <ariya at kde.org> wrote:
> > >  And if you change it (intentionally or not), what happens ? Anything ?
> >
> >  You can't. It will give a compile error.
>
> Yes, i know. And not only it's orthogonal to this thread, but it begs
> a more fundamental question: why would anyone ever try to modify a
> function argument passed by value. I think the point of the thread was
> about whether or not to allow constness mismatches in function
> arguments in the declaration and  the definition.
>
> I'm still waiting for a technical rationale for ever doing either of these.

If a parameter is used as given I like many would prefer it to be const, so 
the compiler can help me to detect unwanted assignements.

But in functions which limit parameters to valid ones non-const parameters can 
be reused, instead of having to use some more parameter (names).

void foo::remove( int from, int to )
{
	// a lot of checks here with to, e.g.
	if( to >= mLength )
		to = mLength - 1;
}
vs.
void foo::removed( const int from, const int toValueWhichCouldBeInvalid )
{
	int toValueInCheck = toValueWhichCouldBeInvalid;
	// a lot of checks here with toValueInCheck, e.g.
	toValueInCheck = ( toValueInCheck >= mLength ) ?
		mLength - 1 : toValueInCheck;
	const int toValueWhichIsValid = toValueInCheck;
}

Well, now that I think about this... the later version has it's pro, too. 
Because "to" in the first version is non-const also for the rest of the 
function and not protected against unwanted assignments, while in the second 
it is, if one uses toValueWhichIsValid. Hm. What is the best practise here?

Friedrich, a member of const-as-const-can-be group




More information about the kde-core-devel mailing list