c++ - 在放置新分配的对象时不调用析构函数可以吗?

标签 c++

假设我有一个固定的内存缓冲区

char *buffer; 

然后我使用 placement new 在该缓冲区中分配我的结构

struct S
{ 
    std::tuple<int, double, char> m_data; 
    auto getRecord() 
    { 
        return m_data;
    }
};

S *newS = new(buffer + offset)S; 

我知道我应该手动调用此类分配项的析构函数,但是如果不涉及簿记/资源管理,可以忽略这个吗?换句话说,如果使用缓冲区的类的析构函数没有做任何事情(类似于上面的 ~S()),可以跳过这一步吗?如果是这样的话,我可以在不破坏以前的租户的情况下重用缓冲区吗?

最佳答案

该标准在第 3.8 节 [basic.life] 中有一条规则涵盖了这一点:

A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.

许多专家一致认为“取决于析构函数产生的副作用”过于模糊而无用。许多人将其解释为同义反复,意思是“如果在未评估析构函数副作用时程序具有未定义的行为,则未能调用析构函数会导致未定义的行为”。参见 Observable behavior and undefined behavior -- What happens if I don't call a destructor?

如果您的类型有一个平凡的析构函数(在您的示例中似乎就是这种情况),那么调用它(或未能调用它)没有任何效果——调用一个平凡的析构函数甚至不会结束对象。

The lifetime of an object o of type T ends when:

  • if T is a class type with a non-trivial destructor, the destructor call starts, or
  • the storage which the object occupies is released, or is reused by an object that is not nested within o.

也就是说,如果 T 没有非平凡的析构函数,则结束对象 o 生命周期的唯一方法是释放或重用其存储空间。

关于c++ - 在放置新分配的对象时不调用析构函数可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59170932/

相关文章:

c++ - 难以理解 free() 的行为

c++ - CMake 无法找到对应于 "Unix Makefiles"的构建程序

c++ - 使用多线程处理 SIGTERM 的正确方法

c++ - 高级 C++ 多括号

c++ - C++对象之间的通信

c++ - VSCode c++ task.json包含路径和库

c++ - 转换到较窄的 const 位置时是否暗示转换到 const?

c++ - 从QAbstractItemModel正确删除子树

c++ - 为什么我们在 C++ 中使用 printf() 函数?

c++ - "Rename"派生类中的成员变量