已建立(见下文)放置 new
是创建对象所必需的
int* p = (int*)malloc(sizeof(int));
*p = 42; // illegal, there isn't an int
然而,这是在 C 中创建对象的一种非常标准的方式。
问题是,如果int
是用C创建的,然后返回C++,是否存在?
换句话说,以下内容是否保证是合法的?假设 int
对于 C 和 C++ 是相同的。
foo.h
#ifdef __cplusplus
extern "C" {
#endif
int* foo(void);
#ifdef __cplusplus
}
#endif
foo.c
#include "foo.h"
#include <stdlib.h>
int* foo(void) {
return malloc(sizeof(int));
}
main.cpp
#include "foo.h"
#include<cstdlib>
int main() {
int* p = foo();
*p = 42;
std::free(p);
}
关于展示位置强制性质的讨论链接新
:
- Is placement new legally required for putting an int into a char array?
- https://stackoverflow.com/a/46841038/4832499
- https://groups.google.com/a/isocpp.org/forum/#!msg/std-discussion/rt2ivJnc4hg/Lr541AYgCQAJ
- https://www.reddit.com/r/cpp/comments/5fk3wn/undefined_behavior_with_reinterpret_cast/dal28n0/
- reinterpret_cast creating a trivially default-constructible object
最佳答案
是的!但这仅仅是因为 int
是一种基本类型。它的初始化是空操作:
To default-initialize an object of type T means:
If T is a (possibly cv-qualified) class type, constructors are considered. The applicable constructors are enumerated ([over.match.ctor]), and the best one for the initializer () is chosen through overload resolution. The constructor thus selected is called, with an empty argument list, to initialize the object.
If T is an array type, each element is default-initialized.
Otherwise, no initialization is performed.
强调我的。由于“不初始化”一个 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. The lifetime of an object of type T begins when:
- storage with the proper alignment and size for type T is obtained, and
- if the object has non-vacuous initialization, its initialization is complete,
可以以 C++ 标准可接受的任何方式分配存储空间。是的,即使只是调用 malloc
。否则,使用 C++ 编译器编译 C 代码将是一个非常糟糕的主意。然而,the C++ FAQ has been suggesting it for years .
此外,由于 C++ standard遵从 C standard malloc
的地方。我认为也应该提出措辞。这里是:
7.22.3.4 malloc 函数 - 第 2 段:
The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.
“值是不确定的”部分有点表明那里有一个对象。不然怎么可能有任何值(value),更何况是一个不确定的呢?
关于c++ - 在 C 函数中创建的对象的存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46909105/