c++ - 双重构造是未定义的行为吗?

标签 c++ object c++11 constructor lifetime

在我们的代码库中,使用了一个内存块池,并在“分配”时使用“新位置”构造对象。不过,我错过了析构函数调用,发现允许“双重构造”很奇怪,并且想知道在同一个对象上再次调用构造函数是否是未定义的行为。
在 C++11 3.8.4 [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.


这是否意味着错过析构函数调用实际上是可以的,只要我们谈论具有没有副作用的析构函数的类型?
编辑:上下文是:没有堆的嵌入式软件,自己的容器实现在 c-array-elements 或 byte-arrays 上进行放置新。

最佳答案

您可以在没有 UB 的情况下进行双重构造。新对象是一个完全不同的对象,并且指向旧对象的指针/引用是 UB。
新建放置时很容易绊倒UB,更不用说双重构造时。
不调用析构函数只是意味着对象没有被清理。如果析构函数是微不足道的,这不会有太大的风险。在另一个对象上构造一个对象会结束对象的生命周期,调用析构函数也是如此。
如果对象以正确的类型在自动存储中,则在其上构造不同的对象并退出范围(导致不再存在的原始对象被销毁)通常是 UB(您可以在此处使用原始的微不足道的析构函数来避免 UB对象;这就是为什么字节缓冲区可以在其中完成新的放置)。

关于c++ - 双重构造是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64767734/

相关文章:

c++ - cv::Mat GREY 到 RGBA 并转换为 UIImage

r - 在 R 中迭代生成名称以存储绘图

c++ - unique_ptr 运算符=

javascript - 在对象数组中查找对象下落

c++ - 如何解析 `no viable overloaded operator[] for type ' std::map<AudioTypes, const char *>`?

c++ - 鉴于 C++ 中没有反射,我怎样才能使它更健壮?

c++ - 指针删除崩溃

c++ - 链表插入错误

c++ - C 三重解引用

java - 为什么要创建一个testClass对象