gpt4 book ai didi

c++ - 哪个 union 成员在安置新人后变得活跃

转载 作者:可可西里 更新时间:2023-11-01 15:22:15 25 4
gpt4 key购买 nike

关于这段代码:

#include <string>

int main()
{
union u {
u() { i = 0; }
~u() {}

int i;
std::string s1;
std::string s2;
} u;

new (&u) std::string{};
}

[intro.object]/2

Objects can contain other objects, called subobjects. A subobject can be a member subobject ([class.mem]), a base class subobject ([class.derived]), or an array element. An object that is not a subobject of any other object is called a complete object. If an object is created in storage associated with a member subobject or array element e (which may or may not be within its lifetime), the created object is a subobject of e's containing object if:
— the lifetime of e's containing object has begun and not ended, and
— the storage for the new object exactly overlays the storage location associated with e, and
— the new object is of the same type as e
(ignoring cv-qualification).

没有要求如何在与成员子对象关联的存储中创建对象。如果子对象是标准布局 union 的成员或非 union 类对象的第一个成员,则代码不必在地址运算符的参数中指定子对象。在这种情况下,获取包含对象的地址就足以指定成员子对象的存储。

«没有要求如何创建一个对象»,除此之外,意味着指向新放置的指针不必point到子对象。主要是因为可能没有对象指向(注意,[intro.object]/2 不需要子对象存在)。在 std-discussion 邮件列表中有人询问,给定一个 struct A 类型的对象 x { unsigned char buf[1]; };new (&x) A{}new (x.buf) A{} 有区别吗?和 the answer不是,在这两种情况下,x.buf 都会 provide storage对于 A{}。因为

The wording in [intro.object] and [basic.life] concern themselves with the storage address represented by a pointer, not the object to which it points.


[class.union]/1发誓« union 类型对象的至多一个非静态数据成员可以在任何时候处于事件状态»。

s1s2 哪个在上面的代码中变得活跃?

最佳答案

指针是一个地址,但对于对象模型而言,它不仅仅是一个地址。它指向该地址的特定对象。多个对象可以存在于某个地址,但这并不意味着指向这些对象中的任何一个的指针同时是指向该地址处其他对象的指针。考虑一下 [expr.unary.op]/1 所说的指针间接寻址:

the result is an lvalue referring to the object or function to which the expression points.

不是“那个地址的对象”;它是一个左值,指向被指向的对象。很明显,在 C++ 对象模型中,多个对象可以存在于同一地址,但指向该地址的特定指针并不指向所有这些对象。它只指向其中之一。

[expr.unary.op]/2 表示“一元 & 运算符的结果是指向其操作数的指针”。因此,&u 指向类型为 uu(顺便说一句,真的有必要将对象命名为与类型相同的名称吗? ). &u 不指向 u.iu.s1u.s2。所有这些都保证与 &u 共享相同的地址,但 &u 本身仅指向 u

那么现在的问题就变成了,&u代表的存储是什么?好吧,根据 [intro.object]/1,我们知道“一个对象占用一个存储区域”。如果 &u 指向对象 u,则该指针必须代表该对象占用的存储区域。不存储其任何子对象;它是该对象的存储。完整。

现在,我们进入 new(&u) std::string{}。此表达式在 &u 表示的存储中创建一个 std::string{} 类型的对象。这表示重用对象 u 的存储。根据 [basic.life]/1.4,终止 u 的生命周期。这终止了其事件成员子对象的生命周期。

所以你的问题的答案是两者都没有激活,因为对象 u 不存在了。

关于c++ - 哪个 union 成员在安置新人后变得活跃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54236936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com