const - Best practices

Peter Alexander peter.alexander.au at gmail.com
Sun Jan 2 10:41:16 PST 2011


On 31/12/10 6:33 PM, Peter Alexander wrote:
> Ok, so while I'm still not 100% satisfied with the lack of logical const
> in D, I'm willing to see how far I can get without bitwise const without
> going crazy, and I just want to clarify some things.
>
> Andrei has commented a couple of times on the fact that D's const has
> more guarantees than C++'s const, and as a result you should use it a
> lot less often than you do in C++.
>
> Questions:
>
> 1. What exactly does this mean? What are the situations where you should
> use const in C++, but not in D?
>
> 2. When designing base classes and interfaces, when should you mark a
> member function as const? In C++ you would do so for any accessor, as
> they would be logically const. In D, you can't assume that an accessor
> is bitwise const (due to lazy initialisation and caching), so when do
> you make it const in the base class, and when do you leave it mutable?
>
> 3. When should you take const references in template functions
> (essentially same subquestions as above).
>
> Final note: my intention here is not to start another logical const vs.
> bitwise const war. I just want to know how the differences in const from
> C++ affect library design, and what the best practices for
> const-correctness are in D.
>
> Thanks in advance.

Sorry for the bump, but there's at least three people here that would 
like an answer to this. Surely someone knows how to use const in D? :-)

Additional question: why are none of Object's methods const, e.g. 
toString and toHash?


More information about the Digitalmars-d mailing list