[Issue 17448] Move semantics cause memory corruption and cryptic bugs

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Oct 2 09:28:36 UTC 2018


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

--- Comment #37 from Walter Bright <bugzilla at digitalmars.com> ---
Looking at your example, I rewrote it into a nunnable form:

import core.stdc.stdio;

struct S {
    int i;

    this(int i) {
        printf("this() %d\n", i);
        this.i = i;
    }

    this(this) {
        printf("this(this) %d\n", i);
    }

    ~this() {
        printf("~this() %d\n", i);
    }
}

int main() {
    S s = test(true);
    printf("s %d\n", s.i);
    return 0;
}

S test(bool b) {
    S s1 = S(1), s2 = S(2);
    if (b)
        return s1;
    else
        return s2;
}

You are correct that copy elision does not take place. However, it does not
leave the code in a bad state. Running it yields:

this() 1
this() 2
this(this) 1
~this() 2
~this() 1
s 1
~this() 1

I.e. there are 3 constructions, and 3 destructions. It is correct code. It is
not as efficient as a move constructor, but it is correct and you are not left
with a dangling pointer.

--


More information about the Digitalmars-d-bugs mailing list