Const template

Chris Nicholson-Sauls ibisbasenji at gmail.com
Tue Jan 23 13:45:48 PST 2007


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.

Okay, granted.  (Const instances coming from a pool rather than newly created, for 
example.)  So, a new question, can the const constructors call the "normal" constructors? 
  Aka:

class Foo {
   this () { /* ... do stuff ... */ }

   this(const) () {
     // ... yadda yadda
     this();
     // ... yadda yadda
   }
}

And what else might possible gain this odd 'func(attr)(...)' notation later?  Its... 
interesting, to be sure.  But certainly better to my eyes than 'func (...) const' and 
company ever were.

>> # 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

Actually this was inadvertantly answered for me when I read elsewhere in the thread of the 
notion of const playing a part in implicit casting, namely that mutable->const is valid 
while const->mutable is not.  Just had a dull brain moment, I suppose.  :)

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list