是否可以将C ++智能指针与C的malloc一起使用? [英] Is it possible to use a C++ smart pointers together with C's malloc?
问题描述
我的某些代码仍然使用malloc
而不是new
.原因是因为我怕使用new
,因为它会抛出异常,而不是返回我可以轻松检查的NULL
.将每个对new
的调用包装在try{}catch(){}
中看起来也不太好.而使用malloc
时,我只能执行if (!new_mem) { /* handle error */ }
.
Some of my code still uses malloc
instead of new
. The reason is because I am afraid to use new
because it throws exception, rather than returning NULL
, which I can easily check for. Wrapping every call to new
in a try{}catch(){}
also doesn't look that good. Whereas when using malloc
I can just do if (!new_mem) { /* handle error */ }
.
因此,我有一个问题.我可以将智能指针与malloc
一起使用吗?
Therefore I have a question. Can I use smart pointers together with malloc
?
类似的东西:
SmartPointer<Type> smarty = malloc(sizeof(Type));
类似这样的东西.
这可能吗?
感谢Boda Cydo.
Thanks, Boda Cydo.
推荐答案
如果使用的是shared_ptr
或unique_ptr
,则可以指定自定义删除器.例如,
If you are using shared_ptr
or unique_ptr
, you can specify a custom deleter. For example,
struct free_delete
{
void operator()(void* x) { free(x); }
};
这可以与shared_ptr
一起使用,如下所示:
This can be used with shared_ptr
like so:
std::shared_ptr<int> sp((int*)malloc(sizeof(int)), free_delete());
如果使用的是unique_ptr
,则删除器是unique_ptr
类型的一部分,因此需要将删除器指定为模板参数:
If you are using unique_ptr
, the deleter is a part of the unique_ptr
's type, so the deleter needs to be specified as a template argument:
std::unique_ptr<int, free_delete> up((int*)malloc(sizeof(int)));
但是,在编写C ++时,尤其是在分配失败方面,最好正确使用异常而不是避免使用异常.在大多数情况下,您无法从尝试执行分配的函数中分配失败中成功恢复,因此异常可以帮助您在实际有能力处理错误的地方进行处理.
However, it is better to use exceptions correctly, rather than avoiding them, when writing C++, especially with respect to allocation failures. In most cases, you cannot successfully recover from an allocation failure in the function trying to do the allocation, so exceptions can help you to handle the error where you are actually capable of handling it.
这篇关于是否可以将C ++智能指针与C的malloc一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!