Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

emplace mutates immutable data in @safe code #17219

Open
dlangBugzillaToGithub opened this issue Oct 4, 2024 · 0 comments
Open

emplace mutates immutable data in @safe code #17219

dlangBugzillaToGithub opened this issue Oct 4, 2024 · 0 comments
Labels

Comments

@dlangBugzillaToGithub
Copy link

Paul Backus (@pbackus) reported this on 2024-10-04T16:45:52Z

Transferred from https://issues.dlang.org/show_bug.cgi?id=24795

Description

As of DMD 2.109.1, the example program below compiles and runs to completion without errors.

The program uses core.lifetime.emplace to mutate immutable data in @safe code. Since mutating immutable data results in undefined behavior, it is a bug for the program to compile.

The cause of the bug is the use of @trusted in core.lifetime.emplace to cast away type qualifiers from the target object.

---
import core.lifetime;

void example1() @safe
{
    const(int)* obj = new immutable(int)(123);
    assert(*obj == 123);
    emplace(obj, 456);
    assert(*obj == 456); // immutable object mutated!
}

void example2() @safe
{
    static class C
    {
        int n;
        this(int n) pure @safe { this.n = n; }
    }

    const(C) obj = new immutable(C)(123);
    assert(obj.n == 123);
    emplace(obj, 456);
    assert(obj.n == 456); // immutable object mutated!
}

void example3() @safe
{
    static struct S
    {
        int n;
        this(int n) pure @safe { this.n = n; }
    }

    const(S)* obj = new immutable(S)(123);
    assert(obj.n == 123);
    emplace(obj, 456);
    assert(obj.n == 456); // immutable object mutated!
}

void main() @safe
{
    example1();
    example2();
    example3();
}
---
@thewilsonator thewilsonator added the Druntime Specific to druntime label Dec 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants