fix #21161 placement new fails on default-init struct (#21212)

This commit is contained in:
Walter Bright 2025-04-12 05:21:01 -07:00 committed by GitHub
parent d66ef6a26d
commit 346a772985
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 36 additions and 6 deletions

View file

@ -1277,7 +1277,7 @@ elem* toElem(Expression e, ref IRState irs)
if (ne.placement) if (ne.placement)
{ {
ex = toElem(ne.placement, irs); ex = toElem(ne.placement, irs);
ex = addressElem(ex, tclass, false); //ex = addressElem(ex, tclass, false);
} }
else if (auto lowering = ne.lowering) else if (auto lowering = ne.lowering)
// Call _d_newitemT() // Call _d_newitemT()
@ -1316,18 +1316,32 @@ elem* toElem(Expression e, ref IRState irs)
/* Structs return a ref, which gets automatically dereferenced. /* Structs return a ref, which gets automatically dereferenced.
* But we want a pointer to the instance. * But we want a pointer to the instance.
*/ */
ez = el_una(OPaddr, TYnptr, ez); if (!ne.placement)
ez = el_una(OPaddr, TYnptr, ez);
} }
else else
{ {
StructLiteralExp sle = StructLiteralExp.create(ne.loc, sd, ne.arguments, t); StructLiteralExp sle = StructLiteralExp.create(ne.loc, sd, ne.arguments, t);
ez = toElemStructLit(sle, irs, EXP.construct, ev.Vsym, false); ez = toElemStructLit(sle, irs, EXP.construct, ev.Vsym, false);
if (tybasic(ez.Ety) == TYstruct) if (tybasic(ez.Ety) == TYstruct && !ne.placement)
ez = el_una(OPaddr, TYnptr, ez); ez = el_una(OPaddr, TYnptr, ez);
} }
//elem_print(ex); static if (0)
//elem_print(ey); {
//printf("ez:\n"); elem_print(ez); if (ex) { printf("ex:\n"); elem_print(ex); }
if (ey) { printf("ey:\n"); elem_print(ey); }
if (ew) { printf("ew:\n"); elem_print(ew); }
if (ezprefix) { printf("ezprefix:\n"); elem_print(ezprefix); }
if (ez) { printf("ez:\n"); elem_print(ez); }
printf("\n");
}
if (ne.placement)
{
ez = el_bin(OPstreq,TYstruct,el_copytree(ev),ez);
ez.ET = ev.ET;
ez = el_una(OPaddr, TYnptr, ez);
}
e = el_combine(ex, ey); e = el_combine(ex, ey);
e = el_combine(e, ew); e = el_combine(e, ew);

View file

@ -93,6 +93,21 @@ void test6()
/*************************************************/ /*************************************************/
struct S7
{
int x = 10;
int y = 20;
}
void test7()
{
S7 t = void;
new (t) S7(10,20);
assert(t.x == 10 && t.y == 20);
}
/*************************************************/
int main() int main()
{ {
test1(); test1();
@ -101,6 +116,7 @@ int main()
test4(); test4();
test5(); test5();
test6(); test6();
test7();
return 0; return 0;
} }