Const template

Andrei Alexandrescu (See Website For Email) SeeWebsiteForEmail at erdani.org
Tue Jan 23 22:22:27 PST 2007


Bruno Medeiros wrote:
> Andrei Alexandrescu (See Website For Email) wrote:
>> Chris Nicholson-Sauls wrote:
>>> So then I ask, why have const constructors/destructors?  What, given 
>>> an (even contrived) example, would be the likely difference in code 
>>> between constant and non-constant constructors/destructors?  And how 
>>> is this:
>>
>> A constructor might take different decisions on caching, preallocating
>> etc. when it prepares for mutability, as opposed to it knowing that the
>> object won't change. For example, creating a const deque might cause a 
>> different allocation strategy than a non-const one.
>>
>>> # Foo f = new const Foo;
>>>
>>> Different from this: # const Foo f = new Foo;
>>
>> In the latter case you are robbing the constructor from a little piece 
>> of information. Things will still work.
>>
>>
>> Andrei
> 
> I was about to ask the same that Chris N.S. did. So how about a 
> destructor, what would a const destructor differ from a normal one? 
> Perhaps to destroy the const object in cases where such object was 
> created in such a way that the normal destructor no longer correctly 
> knows how to destroy the const object? Seems reasonable but I can't 
> think of an example of the top of my head.

If a const constructor does things a different way than the non-const 
constructor, it follows that the const destructor might need to "undo" 
things differently too. E.g., a const constructor can use sharing among 
all const instances. Consequently, the const destructor must know this 
so it doesn't assume it owns the object's resources.

Andrei



More information about the Digitalmars-d mailing list