Skip to content

Placement new doesn't count as 'initialisation' #21203

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

Closed
TurkeyMan opened this issue Apr 11, 2025 · 4 comments
Closed

Placement new doesn't count as 'initialisation' #21203

TurkeyMan opened this issue Apr 11, 2025 · 4 comments
Assignees

Comments

@TurkeyMan
Copy link
Contributor

struct Y
{
    this() @disable; // default disabled
    this(int) {}
}

struct S
{
    Y m;

    this(int x)
    {
        new(m) Y(x); // initialise `m`
    }
}
error : field `m` must be initialized in constructor

m was initialised by explicit constructor call.

@TurkeyMan
Copy link
Contributor Author

@WalterBright there's a few of these backing up... getting harder to make progress.
I'm sure they're all trivial.

@kinke
Copy link
Contributor

kinke commented Apr 14, 2025

I doubt this is trivial - a placement-new might not initialize the whole member, but just a portion of it. Think of a static array being initialized with multiple placement-new (or just partially with a single one).

The first assignment to a member in a ctor is special, is always a construction (not an assignment). So I hope we don't really need ugly placement-new in ctors.

@WalterBright
Copy link
Member

I haven't looked at the logic for constructor initialization in 15+ years :-)

For the moment, it can be worked around by simply initializing m before its use in the placement new.

@TurkeyMan
Copy link
Contributor Author

The first assignment to a member in a ctor is special...

Yes, I know. Could that 'first assignment' logic be tickled also by being the argument to a placement new expression? Calling placement new on something should be equivalent to the init assignment. I guess the init assignment must just flag a bool; passing to a placement new could just flag the same bool? That's all that would be needed.

For the moment, it can be worked around by simply initializing m before its use in the placement new.

  1. That fails for things with this() @disable, which is what alluded me to the issue.
  2. It's theoretically invalid, because placement new should only be called on UNINITIALISED memory; it's improper to initialise first.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants