Is it possible to use a C++ smart pointers together with C's malloc?

Viewed 19910

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.

10 Answers

for oneliner: unique_ptr<char, void (*)(void*)> buffer( (char*)malloc(size), free );

Related