<分区>
这段代码在 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 ...
我相当确定这句话回答了我的问题,但我对它的理解还不够好,无法判断它是说是还是不是。