Const template

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


Frits van Bommel wrote:
> Let's talk about references for a bit first. You have "normal" (mutable) 
> references and const references.

Yah.

> When you create an object, you get a 
> mutable reference by default, or a const reference if you ask for it 
> ("new const C"). Normal references implicitly convert to const 
> references, but not the other way around.

Yah.

> I just figured that an object created by "new const" would be a "const 
> object", since no non-const references to it are possible without 
> invoking undefined behavior (e.g. using pointer casts). Therefore it 
> can't be modified.

In D, an object created with "new const" is exactly like the proverbial 
tree falling in the forest: it's actually not const, but nobody can 
change it, so nobody can tell.

>> The downside of this relaxation is that aliasing might stick its nose. 
>> My conjecture is that in the vast majority of cases it can be 
>> trivially proved (by the compiler) that no aliased access can affect 
>> const data. And even in the cases where the compiler must generates 
>> conservative code (as it does today in 100% of the cases), the benefit 
>> to the programmer still justifies this more relaxed view of immutability.
> 
> For D, you may be right because of the way modules work; the compiler 
> will often have the source to all functions called.
> For C++ that conjecture will often be wrong, simply because the 
> implementation of functions called will often be in a source file the 
> compiler can't see (it has only seen the header).
> 
> The compiler needs to either see every variable accessible from called 
> functions (to make sure they can't contain or (transitively) reference 
> an alias) or know for certain that no mutable references accessible to 
> called functions exist (because it sees the allocation and the 
> implementation of every function it may have been mutably passed to).
> Or maybe there's another way to be sure it won't be modified that I 
> didn't think of, but I don't think there's any way to be sure if it's 
> ever been a mutable parameter to an unseen function and another unseen 
> function is then called.

Something like that. Don't forget, however, that exceedingly few 
optimizations make assumptions across a function call. In the most 
frequent case, you just want to make sure that some data is immutable 
over a short burst of primitive operations. I think this is easily doable.


Andrei



More information about the Digitalmars-d mailing list