What does C++ do better than D? - StackOverflow.com

Jonathan M Davis jmdavisProg at gmx.com
Mon Aug 1 18:33:55 PDT 2011


On Monday 01 August 2011 18:02:11 Walter Bright wrote:
> On 8/1/2011 5:58 PM, Jonathan M Davis wrote:
> >> On 8/1/2011 5:07 PM, Jonathan M Davis wrote:
> >>> You do get some gains from const in C++, but it's pretty much all
> >>> gained by convention. It _is_ better than just comments in that the
> >>> compiler will complain if you break the convention, forcing you to
> >>> explicitly break it (e.g. via casting or mutable), but ultimately,
> >>> it doesn't enforce much. I do believe that it enforces enough that
> >>> it's worth having, but it obviously doesn't provide the guarantees
> >>> that D's const does.
> >> 
> >> Any code at any time can modify a mutable member of a const object,
> >> without even bothering with the nicety of a cast. The notion that C++
> >> "supports" logical const is without merit.
> > 
> > If an object isn't const, you can't call anything on it that isn't
> > const. That does gain you some level of safety which is enforced by the
> > compiler.
> Those "const" functions can still change the mutable members without any
> cast.

Yes. I agree with you that C++ does not ultimately give you any guarantees, 
because you can use casting and mutable to completely circumvent const. 
However, I disagree with you if you think that const in C++ isn't ultimately 
any better than commenting your code to say that it's const. The compiler does 
enforce const on some level - it just gives you ways to completely circumvent 
it if you want to - so while it is ultimately a convention, it is on some 
level a compiler-enforced convention. So, it's better than comments. That's 
all I'm really trying to say.

Just the other day, the fact that I use const heavily in C++ helped me catch 
bugs in my code where I had gotten the arguments to algorithm's copy function 
backwards. The fact that the source was const made it so that copy didn't 
compile. Without const, I would have had a much harder time catching my 
mistake.

So yes. It's ultimately a fallacy to say that C++ has logical const. However, 
that doesn't mean that const in C++ is useless. And your posts on it at least 
give the impression that that's what you think. It does not give the same 
guarantees as D's const, but it does give you some (albeit much weaker 
guarantees) and is better than nothing.

- Jonathan M Davis


More information about the Digitalmars-d mailing list