gpt4 book ai didi

c++ - 复制空对象是否涉及访问它

转载 作者:IT老高 更新时间:2023-10-28 22:30:29 27 4
gpt4 key购买 nike

灵感来自 this问题。

struct E {};
E e;
E f(e); // Accesses e?

access是要

read or modify the value of an object

空类有 implicitly defined copy constructor

The implicitly-defined copy/move constructor for a non-union class X performs a memberwise copy/move of its bases and members. [...] The order of initialization is the same as the order of initialization of bases and members in a user-defined constructor. Let x be either the parameter of the constructor or, for the move constructor, an xvalue referring to the parameter. Each base or non-static data member is copied/moved in the manner appropriate to its type:

  • [...] the base or member is direct-initialized with the corresponding base or member of x.

最佳答案

我认为最准确地描述执行访问的标准部分是 [basic.life]。在本段中,解释了使用引用或指向超出其生命周期的对象的指针可以做什么。授权对此类实体进行的所有操作都不会执行对对象值的访问,因为此类值不存在(否则标准将不一致)。

所以我们可以举一个更激烈的例子,如果这不是未定义的行为,那么你的示例代码中就无法访问 e (根据上面的推理):

struct E{
E()=default;
E(const E&){}
};
E e;
e.~E();
E f(e);

这里的e 是一个生命周期已经结束但其存储空间仍在分配的对象。 [basic.life]/6 中描述了使用这种左值可以做什么。

Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways. For an object under construction or destruction, see [class.cdtor]. Otherwise, such a glvalue refers to allocated storage ([basic.stc.dynamic.deallocation]), and using the properties of the glvalue that do not depend on its value is well-defined. The program has undefined behavior if:

  • an lvalue-to-rvalue conversion ([conv.lval]) is applied to such a glvalue,

  • the glvalue is used to access a non-static data member or call a non-static member function of the object, or

  • the glvalue is implicitly converted ([conv.ptr]) to a reference to a base class type, or

  • the glvalue is used as the operand of a static_cast ([expr.static.cast]) except when the conversion is ultimately to cv char& or cv unsigned char&, or

  • the glvalue is used as the operand of a dynamic_cast ([expr.dynamic.cast]) or as the operand of typeid.

上面提到的点都没有发生在 E 复制构造函数中,所以这个答案中的示例代码定义明确,这意味着无法访问被破坏对象的值。因此,您的示例代码中无法访问 e

关于c++ - 复制空对象是否涉及访问它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48341888/

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