How to turn an inout(Object) into a string

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Apr 25 22:40:33 PDT 2015


On Sunday, April 26, 2015 05:09:30 Meta via Digitalmars-d-learn wrote:
> On Sunday, 26 April 2015 at 04:52:36 UTC, Jonathan M Davis wrote:
> > It's only undefined if mutation is involved, though I don't
> > know if mutation is involved in this case or not
>
> I was thinking that a class can define an arbitrary toString()
> that modifies it some of its member variables, which definitely
> breaks const-correctness.
>
> class CustomToString
> {
>      int n;
>
>      override string toString()
>      {
>          n = 1;
>
>          return "Uh oh";
>      }
> }
>
> void main()
> {
>      import std.stdio;
>
>      immutable c = new CustomToString();
>      writeln(cast()c);
> }

Yes. That's legal and would be one reason to not just cast away const on an
Object and call toString on it. It's just that in the example given, an
immutable Object was constructed directly, and Object's toString isn't going
to mutate anything. The question would be whether the call to writeln would
(and it shouldn't). So, in the OP's code, I don't think that it's actually a
problem, but in general, it could be, so it's ill-advised to cast away const
- certainly, if you're going to, you need to be sure that mutation isn't
going to occur to the object from which you cast away const.

But I'd also argue that almost no code should be using Object for much of
anything anyway. In theory, we're going to get rid of most of the functions
on Object at some point here, at which point, Object won't be much more than
a void* specific to class objects. And the implementations of those
functions on Object are pretty useless anyway.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list