D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 7130 - NRVO Bug: Wrong Code With D'tor + Conditional Return
Summary: NRVO Bug: Wrong Code With D'tor + Conditional Return
Status: RESOLVED DUPLICATE of issue 7516
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: Other Linux
: P2 critical
Assignee: No Owner
URL:
Keywords: wrong-code
Depends on:
Blocks:
 
Reported: 2011-12-18 17:23 UTC by David Simcha
Modified: 2012-05-10 23:05 UTC (History)
0 users

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description David Simcha 2011-12-18 17:23:26 UTC
import core.stdc.stdio;

struct S {
    this(this) {
        printf("Postblit\n");
    }
    
    ~this() {
        printf("D'tor\n");
    }
}

S doIt(int i) {
    S s1;
    S s2;
    printf("s1 lives at %p.\n", &s1);
    printf("s2 lives at %p.\n", &s2);
    return (i == 42) ? s1 : s2;
}

void main() {
    auto s = doIt(3);
    printf("s lives at %p.\n", &s);
}

Output:

s1 lives at 0xffc54368.
s2 lives at 0xffc54369.
D'tor
D'tor
s lives at 0xffc5437c.
D'tor

Both D'tors are called and the returned result lives at a different address after being returned than before, as expected if not using NRVO.  On the other hand, no postblit being called for whichever struct is returned, as expected if using NRVO.
Comment 1 Kenji Hara 2012-05-10 23:05:16 UTC
(In reply to comment #0)
> Both D'tors are called and the returned result lives at a different address
> after being returned than before, as expected if not using NRVO.  On the other
> hand, no postblit being called for whichever struct is returned, as expected if
> using NRVO.

The function 'doit' cannot NRVO, because &s1 and &s2 should have different addresses.

S doIt(int i) {
    S s1;
    S s2;
    printf("s1 lives at %p.\n", &s1);
    printf("s2 lives at %p.\n", &s2);
    return (i == 42) ? s1 : s2;   // postblit should run
}

I'll make this a dup of bug 7516. I have posted more better test code in there.

*** This issue has been marked as a duplicate of issue 7516 ***