gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:33:17 25 4
gpt4 key购买 nike

<分区>

这段代码在 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

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

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