Const template

Andrei Alexandrescu (See Website For Email) SeeWebsiteForEmail at erdani.org
Tue Jan 23 11:00:38 PST 2007


Frits van Bommel wrote:
> Andrei Alexandrescu (See Website For Email) wrote:
>> Frits van Bommel wrote:
>>> Deletion of a const reference will be necessary for const objects at 
>>> the very least (since there are no non-const references to them). 
>>> Presumably, that's what the "const destructor" is for.
>>>
>>> A case could be made for disallowing explicit deletion of const 
>>> references, but that would mean const objects would only be deletable 
>>> by the GC. That, in turn would mean const objects would be unusable 
>>> by people who need (or just prefer) the GC to be disabled...
>>> Perhaps this should be more of a "best practice" instead of a 
>>> language rule?
>>
>> Deletion of pointers to const data has always been a sticky issue in 
>> C++. There are good arguments either way. I think it should be 
>> disallowed, otherwise a caller passing a const class object does not 
>> have a guarantee that the callee didn't mutate the object, which is 
>> the very purpose of the entire scaffolding.
> 
> But as I mentioned, there will only be const references to const 
> instances, so that would mean const objects couldn't be explicitly deleted.
> And there are people who prefer or need to work with GC off. This 
> limitation would deny them the use of const objects (unless they like 
> memory leaks ;) ).

I disagree. If you want to disable the GC, that doesn't mean you can't 
use const. You use a private non-const reference for ownership purposes, 
and you use a const reference for publishing purposes:

Widget owned = new Widget;
const Widget publicized = owned;
... use publicized wherever ...
delete owned;

This is IMHO entirely reasonable.

> For that reason, I think it should maybe merely be very rude to delete a 
> const reference unless you are absolutely sure nobody else has a 
> reference to the object (that they will ever use), not an error.

I think this might be an acceptable solution, but given the choice, I'd 
stay away from it. I think the C++ experience hasn't shown delete const 
to have any desirable virtues.

Imagine a dialog like this:

"You shot a diplomat with immunity!"
"He's dead. A dead body can't have diplomatic immunity."
"But he was alive and immune when you shot him!"
"But at that point my bullet was in the gun."


Andrei



More information about the Digitalmars-d mailing list