Is it possible to use a C++ smart pointers togethe

2019-01-11 13:22发布

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 */ }.

Therefore I have a question. Can I use smart pointers together with malloc?

Something like:

SmartPointer<Type> smarty = malloc(sizeof(Type));

Something like this.

Is this possible?

Thanks, Boda Cydo.

9条回答
Fickle 薄情
2楼-- · 2019-01-11 13:57

You might want to try "placement new". See What uses are there for "placement new"?

查看更多
ら.Afraid
3楼-- · 2019-01-11 14:01

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); }
};

This can be used with shared_ptr like so:

std::shared_ptr<int> sp((int*)malloc(sizeof(int)), free_delete());

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)));

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.

查看更多
叼着烟拽天下
4楼-- · 2019-01-11 14:04

What code goes in /* handle error */? Is there anything you can actually DO with an out-of-memory error? I just let the application terminate with a call stack (core dump) so I have an idea at least one possible place that might be causing problems.

Using malloc to allocate memory for C++ classes and objects is not a good idea because it won't make sure that the constructors are called, possibly leaving you with uninitialized classes that may even crash if they have virtual methods.

Just use new and delete and don't worry about catching the exception, after all running out of memory IS an exceptional case and should not happen in normal runs of the application.

查看更多
登录 后发表回答