为什么使用 XXXX_new 和 XXXX_free 而不是新建和删除?

Why use XXXX_new and XXXX_free over new and delete?

libssh library时,我看到他们特别说

libssh follows the allocate-it-deallocate-it pattern. Each object that you allocate using xxxxx_new() must be deallocated using xxxxx_free()

这是因为它是一个 C 库而不是一个 C++ 库吗?在 C++ 库中,new 和 delete 不存在,或者忘记 new 和 delete 并使用 xxxx_new 和 xxxx_free 模式?如果这是一种常见的做法,它比 new 和 delete 以及调用的构造函数和析构函数有什么好处?

[编辑] 将 link 添加到我在 "libssh library" 上作为 <a> 标签阅读的地方,供那些提问者使用。

Is this something that comes from it being a C library rather than a C++ library where new and delete didn't exist

很可能是的。通常需要完成比 c 代码中 malloc() 可用的普通内存分配更多的初始化。它类似于 new 调用创建的 class/struct 个实例的构造函数。

or is it a common practice to forget about new and delete and manually create and delete objects using the xxxx_new and xxxx_free pattern?

不,这不是 c++ 中的常见做法。

处理动态分配的实例和所有权的方法是使用标准 c++ Dynamic memory management 实用程序中的函数和智能指针 类。

乍一看您提供的 link,您会发现 libssh 使用 xxxx_new() 函数作为组合 allocator/constructor 调用。它实际上只是工厂函数的标准命名。同样,xxxx_free() 充当 destructor/deallocator 组合。

每当库想要为其用户代码提供类型安全的不透明指针时,将分配和构造结合到单个函数调用中是一个好主意:要编译用户代码,编译器只需要知道类型存在并且它不同于任何其他类型。 public header 中不需要完整的 class/struct 声明。

这种方法在 C++ 库中不是很流行,因为它们通常希望它们的 object 表现得像任何普通的 C++ object(这意味着 pointers/references 不能是对编译器不透明)。但是,如果一个库提供了一个 C 接口,这样的工厂函数就不太可能因为用户将指针传递给未初始化的 objects(忘记构造函数调用)而导致你得到奇怪的错误,或者搞砸了你的 [=26] 的分配=]s.