在混合 c 和 c++ 代码中使用运算符 new
Using operator new in mixed c and c++ code
考虑一个混合了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++是不合法的,因为它以下划线开头,后跟大写字母。这些名称(以及包含双下划线的名称)是为编译器和标准库保留的。
相关文章:
- 重载运算符new[]的行为取决于析构函数
- 体系结构x86_64的未定义符号:std:terminate(),typeinfo,运算符delete[],运算符new
- 为什么 std::make_shared 无法编译带有已删除运算符 new 的类型?
- 为什么 std::vector 使用 std::分配器而不是运算符 new 和 delete?
- 运算符 new 的执行顺序和构造函数的参数
- 如何分配适合容纳 T 类型对象的缓冲区(可能过度对齐、可能有运算符 new 等)
- 重载运算符 new 和运算符 delete 带有三个参数
- 为什么运算符"new"需要指针才能工作?
- 重载运算符 new(),为什么构造函数被调用两次?
- 为什么运算符 new[] 为数组的大小分配内存?
- 在混合 c 和 c++ 代码中使用运算符 new
- 重载运算符 new/new[] 删除/删除[] 全局C++
- 为什么允许重新定义全局运算符 new(size_t)?
- 无法访问使用运算符 new() 分配的内存
- 显式调用"运算符 new"后无法访问对象的函数
- c++ 运算符 new[]/delete [] 是否调用运算符 new/delete?
- 崩溃时间(运算符 new(无符号 int)+22)
- 继承类上的运算符new和delete.操作员删除未执行
- 运算符new[]不接收额外的字节
- 如果我在C++中分配一个带有运算符 new[] 的对象数组,但单独释放它们是否仍然构成内存泄漏