c++ - std::malloc 可以创建一个对象吗?总是需要安置新的吗?

标签 c++ language-lawyer

<分区>

这段代码在 C++ 中是否有未定义的行为?

#include <cstdlib>

int main() {
    int *ip = static_cast<int *>(std::malloc(sizeof *ip));
    *ip = 42; //is this accessing an object that has not started its lifetime?
    free(ip);
}

注意事项:
std::malloc has the semantics that it has in C .在 C 中,std::malloc 创建有效的 int,所以它应该是有效的?

The lifetime of an object or reference is a runtime property of the object or reference. An object is said to have non-vacuous initialization if it is of a class or aggregate type and it or one of its subobjects is initialized by a constructor other than a trivial default constructor. [ Note: Initialization by a trivial copy/move constructor is non-vacuous initialization. — end note  ] The lifetime of an object of type T begins when:

(1.1) storage with the proper alignment and size for type T is obtained, and
(1.2) if the object has non-vacuous initialization, its initialization is complete,

except that if the object is a union member or subobject thereof ...

source

我相当确定这句话回答了我的问题,但我对它的理解还不够好,无法判断它是说是还是不是。

最佳答案

您的对象类型为 int ,这不需要非平凡的初始化,因此只需调用 std::malloc 即可满足两个要点.

如果对象需要一个非平凡的构造函数调用,那么new是满足 (1.2) 的方法,如果您想使用 operator new() 以外的分配器那么放置新的是正确的方法。

关于c++ - std::malloc 可以创建一个对象吗?总是需要安置新的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48671993/

相关文章:

c++ - 为什么构造不完整类型的 std::unique_ptr 编译?

c++ - 在全屏模式下设置控制台字体大小

c++ - 使用条件变量超时的读写器锁

c++ - 从 lambda 构造 std::function 参数

python - 为什么下面的代码表现得如此奇怪? Python3.5 与 Python3.6

c++ - 尝试理解模板和名称查找

c++ - 什么时候在空实例上调用成员函数会导致未定义的行为?

c++ - 修复了带引用的内存布局同步变量

c++ - 如何从 OpenCV 中的目录中按顺序读取文件?

c++ 读取xml文件的内容