gpt4 book ai didi

c++ - 在对象被显式销毁但在其内存被释放之前调用成员函数是否合法?

转载 作者:IT老高 更新时间:2023-10-28 23:27:47 26 4
gpt4 key购买 nike

我有这个代码:

struct data {
void doNothing() {}
};

int main() {
data* ptr = new data();
ptr->~data();
ptr->doNothing();
::operator delete(ptr);
}

请注意,doNothing() 是在对象被销毁之后但在其内存被释放之前被调用的。看起来“对象生命周期”已经结束,但是指针仍然指向正确分配的内存。成员函数不访问任何成员变量。

在这种情况下,成员函数调用是否合法?

最佳答案

是的,对于 OP 中的代码。因为析构函数是微不足道的,调用它并不会结束对象的生命周期。 [basic.life]/p1:

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.

[class.dtor]/p5:

A destructor is trivial if it is not user-provided and if:

  • the destructor is not virtual,
  • all of the direct base classes of its class have trivial destructors, and
  • for all of the non-static data members of its class that are of class type (or array thereof), each such class has a trivial destructor.

不,一般情况下不会。在对象的生命周期结束后调用非静态成员函数是 UB。 [basic.life]/p5:

[A]fter the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that refers to the storage location where the object will be or was located may be used but only in limited ways. For an object under construction or destruction, see 12.7. Otherwise, such a pointer refers to allocated storage (3.7.4.2), and using the pointer as if the pointer were of type void*, is well-defined. Indirection through such a pointer is permitted but the resulting lvalue may only be used in limited ways, as described below. The program has undefined behavior if:

  • [...]
  • the pointer is used to access a non-static data member or call a non-static member function of the object, or
  • [...]

关于c++ - 在对象被显式销毁但在其内存被释放之前调用成员函数是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30310299/

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