在混合 c 和 c++ 代码中使用运算符 new

Using operator new in mixed c and c++ code

本文关键字:运算符 new 代码 混合 c++      更新时间:2023-10-16

考虑一个混合了C和C++代码的程序。C++ 部分包含一个类,该类动态分配 C 样式typedef struct。最小示例:

obj.h(C 代码)

typedef struct _Ctype {
int i;
} Ctype;

class.hpp(C++ code)

struct A {
struct _Ctype *x;
A(int i);
~A();
};

类.cpp(C++代码)

#include "class.hpp"
extern "C" {
#include "obj.h"
}

A::A(int i)
{
x = new struct _Ctype;
x->i = i;
}
A::~A()
{
delete(x);
}

主.cpp(C++代码,主程序)

#include "class.hpp"
int main()
{
A a(3);
return 0;
}

(这个设计的理由来源于这个答案)

使用new表达式来分配 C 样式类型struct _Ctype是否安全(即没有 UB),如上面的代码所示,还是应该更好地使用 C 样式malloc/free

类.cpp(C++代码,替代)

#include <cstdlib>
#include "class.hpp"
extern "C" {
#include "obj.h"
}

A::A(int i)
{
x = (struct _Ctype *)malloc(sizeof(struct _Ctype));
x->i = i;
}
A::~A()
{
free(x);
}

加法

在下面的一些评论之后澄清问题:在上面的最小示例中,所有代码都使用 C++ 编译器编译。但是,可以考虑将C++代码与 C 库结合使用。然后可以按如下方式重新表述该问题:

  • 如果我通过C++代码为 C 样式的typedef struct分配内存,C 库是否可以安全地使用分配的变量?如果是这样,上面给出的替代方案是否安全?

请注意,还可以考虑通过 C 函数为Ctype分配内存,以便C++代码仅管理指向它的指针,例如:

obj.h(C 代码)

typedef struct _Ctype {
int i;
} Ctype;
Ctype *allocate_Ctype();
void deallocate_Ctype(Ctype* p);

obj.C(C 代码)

#include <stdlib.h>
#include "obj.h"
Ctype *allocate_Ctype()
{
return (Ctype *)malloc(sizeof(Ctype));
}
void deallocate_Ctype(Ctype *p)
{
free(p);
}

类.cpp(C++代码)

#include "class.hpp"
extern "C" {
#include "obj.h"
}

A::A(int i)
{
x = allocate_Ctype();
x->i = i;
}
A::~A()
{
deallocate_Ctype(x);
}

(注意:当然A类的复制构造函数和运算符赋值需要正确定义,代码作为问题的说明)

只要释放只发生在您的控制下并使用delete表达式,就完全没有问题。与结构交互的 C 代码不关心它是如何分配的。

旁注:名称_Ctype在C++是不合法的,因为它以下划线开头,后跟大写字母。这些名称(以及包含双下划线的名称)是为编译器和标准库保留的。