[Issue 24561] New: inout on opAssign allows you to mutate member variables

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri May 24 06:49:03 UTC 2024


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

          Issue ID: 24561
           Summary: inout on opAssign allows you to mutate member
                    variables
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: normal
          Priority: P1
         Component: dmd
          Assignee: nobody at puremagic.com
          Reporter: issues.dlang at jmdavisProg.com

This code compiles

---
void main()
{
    static struct V {
        int _data;

        ref opAssign(T)(auto ref T rhs) inout
            if(is(immutable T == immutable V))
        {
            this._data = rhs._data;
            return this;
        }
    }

    V v;
    auto u = v;
    v = u;
}
---

However, it really shouldn't, because inout could be const or immutable
underneath the hood. If the opAssign is not templated, then it correctly gives
an error, but it doesn't if it's templated like here.

That being said, the compiler still manages to give an error for the assignment
to v if v is marked as const, so that may be why the issue hasn't been caught
previously.

This may or may not be related to
https://issues.dlang.org/show_bug.cgi?id=12793, which points to a similar
problem but specifically with a this This template parameter.

--


More information about the Digitalmars-d-bugs mailing list