gpt4 book ai didi

c++ - 显式析构函数调用后此赋值是否无效?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:03:49 25 4
gpt4 key购买 nike

我遇到过一些旨在在不重新分配内存的情况下就地替换对象的代码:

static void move(void* const* src, void** dest) {
(*reinterpret_cast<T**>(dest))->~T();
**reinterpret_cast<T**>(dest) = **reinterpret_cast<T* const*>(src);
}

这对我来说看起来像 UB,因为对象被销毁然后分配给而不被构造,即它需要只是复制分配(仅第二行)或显式破坏(第一行)然后放置 -新的拷贝构造而不是赋值。

我之所以问,是因为虽然这对我来说似乎是一个明显的错误,但它已经存在了一段时间 boost::spirit::hold_any和原来的cdiggins::any它基于它。 (我已经在 Boost 开发人员邮件列表上询问过这个问题,但在等待回复的同时,如果确实不正确,我希望在本地修复这个问题。)

最佳答案

假设 reinterpret_cast s 是明确定义的(即 dest 实际上是指向 T 的指针),标准将对象生命周期的结束定义为:

The lifetime of an object of type T ends when:

  • if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
  • the storage which the object occupies is reused or released.

然后它对使用 glvalue **reinterpret_cast<T**>(dest) 可以做什么给出了一些限制。 :

Similarly, [...] 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. [...] The program has undefined behavior if:

  • an lvalue-to-rvalue conversion (4.1) 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 (4.10) to a reference to a base class type, or
  • the glvalue is used as the operand of a static_cast (5.2.9) 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 (5.2.7) or as the operand of typeid.

添加了强调。

如果对象没有因为它有一个普通的析构函数而进入死后状态,那没有问题。但是,对于任何 T这是一个具有非平凡析构函数的类类型,我们知道赋值运算符被认为是一个成员函数 operator=那个类的。通过此泛左值调用对象的非静态成员函数会导致未定义的行为。

关于c++ - 显式析构函数调用后此赋值是否无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15359654/

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