char *buffer;
我使用placement new在缓冲区中分配我的结构
struct S { std::tuple<int,double,char> m_data; auto getRecord() { return m_data; } }; S *newS = new(buffer + offset)S;
我知道我应该手动调用这些已分配项目的析构函数,但是如果没有涉及bookeeping /资源管理,是否可以省略它?换句话说,如果使用缓冲区的类的析构函数没有做任何事情(类似于上面的~S())是否可以跳过这一步骤?如果是这种情况,我可以重用缓冲区而不破坏以前的租户吗?
解决方法
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 typeT
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
.