extragear/multimedia/amarok/src

Jeff Mitchell kde-dev at emailgoeshere.com
Thu Oct 23 04:34:53 CEST 2008


Ian Monroe wrote:
> On Wed, Oct 22, 2008 at 8:21 PM, Jeff Mitchell
> <kde-dev at emailgoeshere.com> wrote:
>> No, it's not ignored...trying to modify the object without const casting
>> it will result in a compile error.
>>
>> For that reason, it's not misleading either.  The const is a warning to
>> the caller that they should not be modifying that object, and since the
>> compiler will force this upon them, it's far from misleading; it's very
>> direct and specific.
> 
> You can't modify an int or a long.
> 
> You can modify a QString, though it's a copy so you wouldn't be
> modifying the original. I suppose I could see it being good for
> legibility assuming the compiler would actually error out with
> 
>  QString hello = blah.world();
> 
> Where world was defined as 'const QString world();'
> 
> I've never seen such an error before.

Ok, we're all kind of right.  Your example is right above; my example in
my original email was also right; Soren's patch is also right.

My claims about compiler failure were based on my experiences with const
return values; these experiences have always been with pointers,
however.  The examples I put in my original email (which use pointers)
are correct, and will cause compiler errors; what I didn't realize is
that this behavior does not carry through to non-pointer types.

I'm not sure why it wouldn't...I would think it would make sense to
enable that kind of consistency, since (as I've said) you can use it
(with a pointer at least) as a warning to the caller not to modify the
object (unless they are really insistent).  There may be instances where
you don't want even a copy of the object to be modified haphazardly (for
instance if they contain key values that should not be overwritten).

An interesting takeaway from all this:  if you *do* want to force
callers to have to const_cast away a const return value, to ensure they
do not haphazardly modify an object, declare your return value on the
heap and return a pointer:

using namespace std;

const string world()
{
	return "blah";
}

...

string myString = world(); //ok

is fine, but

const string* world()
{
	return new string( "blah" );
}
string* myString = world();  //dies during compile

Might come in handy someday.

--Jeff


More information about the Amarok-devel mailing list