immutability and constness
Ali Çehreli
acehreli at yahoo.com
Thu Jul 12 07:42:16 PDT 2012
On 07/12/2012 07:13 AM, Minas wrote:
> Thanks a lot!
> So what is the problem with (logical)const? Is it needed that
> much? And why some methods (toString(), toHash()) HAVE to be
> const? I mean, what's the problem if they aren't?
Here is the problem:
class C
{}
// Good foo: Takes as const(C) because it is not going to
// change the object
void foo(const(C) c)
{
c.toString();
/*
* With dmd 2.059:
*
* Error: function object.Object.toString() is not
* callable using argument types () const
*/
}
void main()
{}
Notes:
1) The current attempt of making toString() and friends const would fix
that problem.
2) It brings a limitation: What job does the base class have
constraining the derived class's toString()? What if the derived really
needed to mutate the object in toString()?
(That is why I almost never make abstract member functions 'const' in my
C++ coding. Base can't know mutability needs of the derived.)
3) [This warrants another thread or even an article.] You may argue that
foo() API is problematic because despite the sensible const(C), which
nicely binds to mutable and immutable, it cannot be forwarded
efficiently to another function that takes an immutable:
class C
{}
void foo(const(C) c)
{
bar(c);
/* Error: function deneme.bar (immutable(C) c) is not
* callable using argument types (const(C))
*/
}
void bar(immutable(C) c)
{}
void main()
{}
But what if the c that foo() took was immutable to begin with? foo()'s
const(C) parameter erases that information.
To unerase, it must be a template and its parameter must be smart to
copy if the original object was mutable:
// Warning: Very raw idea!
void foo(T)(CopyableOrForwardableConst!C c)
{
bar(c); // makes an immutable copy if necessary,
zar(c); // or not, depending on
// whether original object c is mutable or immutable
}
Ali
--
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html
More information about the Digitalmars-d-learn
mailing list