mutable destructor? WAT???

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 29 09:05:00 PDT 2016


On 8/28/16 6:35 AM, Dicebot wrote:
> Looks correct to me. This const annotation does not prevent you from
> deleting memory or free'ing external resources - but it does ensure no
> transitive mutations for data reachable from struct fields. If it
> allowed destroying with mutable destructor, type system hole like this
> would be legal:
>
> struct S
> {
>     char[] str;
>     ~this() { str[0] = 'a'; }
> }
>
> auto s = new const S("abcd");
> destroy(s); // mutates immutable literal

void foo(const(S) str) {}

void main()
{
     char[1] str = ['0'];
     auto s = S(str[]);
     foo(s);
     writeln(str[]);
}


Clearly non-const destructors can be run on const structs (correctly or 
incorrectly).

Pretty positive that in your example, if you don't destroy s, the GC 
will call the dtor on your "const" struct.

Unsaid in the OP as well is that the given code will work if you don't 
define a destructor.

I'm not sure that this is necessarily a bug in the compiler, however. I 
don't think it should be reasonable to assume a normal function like 
destroy can circumvent attributes.

-Steve


More information about the Digitalmars-d-learn mailing list