将 C 结构工厂函数与其相应的 C++ 包装类构造函数合并
Merging a C struct factory function with its corresponding C++ wrapping class constructor
考虑使用以下内容为 C 库编写一个 C++ 包装器(T
是其他类型):
typedef struct { /*fields*/ } S;
S* alloc_S(const T*);
void free_S(S*);
我想编写一个从S
继承class_S
类,以便分别由于class_S::class_S(const T*)
和class_S::~class_S()
而隐藏对alloc_S
和free_S
的调用(消除了忘记调用free_S
的风险)。
由于alloc_S
已经为其返回的结构的所有字段分配和分配值,因此是否有一种优雅的方法来"围绕"该结构构建class_S
对象的其余部分?
我的目标是避免类似的东西的开销(时间和空间)
class_S::class_S(const T* t)
{
S* tmp = alloc_S(t);
// deep-copy tmp into this
free_S(tmp);
}
显然,与其从S
继承,我可以编写class_S
以拥有一个S*
成员并使用它,但如果可能的话,我想避免这种方法。
这是一种非标准、令人困惑且无法维护的方法 - 请注意特殊的构造语法
#include <memory>
extern "C" {
struct T {};
struct S
{
};
S* alloc_S(T*);
void free_S(S*);
}
struct class_S : S
{
void * operator new (std::size_t, T* p)
{
return alloc_S(p);
}
void operator delete(void *p)
{
if (p) free_S(reinterpret_cast<S*>(p));
}
};
int main()
{
T t;
auto ps = new (&t) class_S;
delete ps;
}
总的来说,您可能最好使用带有自定义删除器的unique_ptr:
struct class_S
{
struct deleter {
void operator()(S*p) const noexcept {
free_S(p);
}
};
class_S(T* p) : impl_(alloc_S(p), deleter()) {}
// add proxy methods as required
std::unique_ptr<S, deleter> impl_;
};
int main()
{
T t;
auto mys = class_S(&t);
}
相关文章:
- 简化在 Pybind11 中为 C++ 模板类生成包装类:模板声明不能出现在块范围内
- C++-用与被包装数据相同的语法构造包装类
- C++-用和结构相同的语法围绕结构构造包装类
- C++泛型包装类,它为某些函数添加了额外的处理
- 如何减少大量包装类的实现代码?
- 在 C++ 中为 C 样式对象创建一个透明包装类
- 如何将包装类的对象用作包装函数中的参数
- 这->...在模板包装类中必需
- 无法理解包装类的构造函数的声明
- 标准向量之上的 C++11 包装类
- 编写安全包装类以管理用户定义对象的指针
- 重构现有包装类,以使用与包装器本身相同的构造函数参数包装 T
- 包装类设计和依赖注入
- 提升 Python 导入失败,未定义包装类的符号
- 简单包装类与智能指针
- 将 C 结构工厂函数与其相应的 C++ 包装类构造函数合并
- 为什么这个C++包装类没有内联掉
- std::variant、包装类和'conversion from ... to non-scalar type ... requested'
- C# 使用包装类中的字符串参数调用 C++ 方法
- 编写值包装类的最佳方式