const - Best practices

Peter Alexander peter.alexander.au at gmail.com
Fri Dec 31 10:33:31 PST 2010


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.


More information about the Digitalmars-d mailing list