[Issue 19430] wrong code for `this =`, corrupted memory issue

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sat Nov 24 15:16:08 UTC 2018


https://issues.dlang.org/show_bug.cgi?id=19430

--- Comment #7 from Stanislav Blinov <stanislav.blinov at gmail.com> ---
What's going on is (pseudo-code) this:

c = S(S.init).opAssign(S.sum(1, 2));

The opAssign is implicitly generated.

Two instances are constructed in-place, one is 'main.s', the other is the
argument to opAssign, no copies are made, no postblits are called.
But then the argument of opAssign is getting destructed, and decrements count
to 0.

So 0 is the correct output here.

For it to be 1, you *need* an explicit opAssign:

void opAssign(S rhs)
{
    if (ptr && *ptr)
        atomicOp!"+="(*ptr, 1);
}

If it were a C++ std::shared_ptr kind of reference count (i.e. not a static
counter), then you'd need this kind of opAssign:

void opAssign(S rhs)
{
   import std.algorithm.mutation : swap;
   swap(ptr, rhs.ptr);
}

--


More information about the Digitalmars-d-bugs mailing list