c++ - 在 C 函数中创建的对象的存在

标签 c++ c language-lawyer object-lifetime

已建立(见下文)放置 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);
}

关于展示位置强制性质的讨论链接:

最佳答案

是的!但这仅仅是因为 int 是一种基本类型。它的初始化是空操作:

[dcl.init]/7 :

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 类似于默认初始化它,它的生命周期在分配存储后开始:

[basic.life]/1 :

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/

相关文章:

c++ - 这个变量将如何初始化?

C 代码在 Windows 上运行(使用 Visual Studio 编译)但不能在 Linux 上编译(使用 gcc)

c - 即使存在逻辑与,这个尾递归是否存在?

c++ - 使用 std::launder 从指向非事件对象的指针获取指向事件对象成员的指针?

c++ - const 和非常量指针的统一包装器

c++ - 如何获取另一个应用程序的所有窗口的句柄

c++ - 删除复制构造函数或复制赋值运算符是否算作 "user declared"?

c++ - 如何判断一个对象是否有堆分配成员?

c++ - 为什么这个函数返回的值与我在内联时返回的值不同?

c++ - 具有共享指针的列表的共享指针