Skip to content

opAssign is not generated for structs with copy constructors #3369

Open
@dlangBugzillaToGithub

Description

@dlangBugzillaToGithub

Jonathan M Davis reported this on 2024-10-25T05:27:39Z

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

Description

If a struct has a postblit constructor but no opAssign, then the compiler will generate an opAssign which calls the postblit constructor so that the assignment behavior matches the copying behavior, e.g.

---
struct S
{
    this(this) {}
}
pragma(msg, __traits(allMembers, S));
---

prints

---
AliasSeq!("__postblit", "__xpostblit", "opAssign")
---

However, copy constructors do not get such an opAssign, e.g.

---
struct S
{
    this(ref S) {}
}
pragma(msg, __traits(allMembers, S));
---

prints

---
AliasSeq!("__ctor")
---

This means that in order for the assignment behavior to match the copying behavior, the user must explicitly declare an opAssign.

https://dlang.org/spec/struct.html#assign-overload explicitly mentions that structs with postblit constructors will have an opAssign generated if one is not declared, but it does not mention anything about copy constructors. So, technically, the current behavior does not violate the spec. However, it's an inconsistency with postblit constructors, and I see no reason why copy constructors should not be treated the same as postblit constructors in this respect. The logic for why postblit constructors get an opAssign seems like it would apply equally to copy constructors.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions