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.
The best solution is to use
new (std::nothrow) Type
. This will act just likenew Type
, but will give null rather than throwing if it fails. This will be much easier than trying to makemalloc
behave likenew
.If you really must use
malloc
, then remember to construct and destruct the object correctly:You can use this with a some smart pointers by giving it a custom deleter:
But this would be much simpler using non-throwing new:
It depends on what the SmartPointer does on destruction. If you can specify
free
as a deallocator, that could work. For example, boost::shared_ptr allows you to specify a deleter.I didn't pay enough attention to your reason for wanting this. I agree with the other answers that using the nothrow
new
is a much better idea.It is possible to use malloc with smart pointers (you have to cast return value to target pointer type, though and provide custom deallocator). But better option is to use
nothrow
version ofnew
operator.http://www.cplusplus.com/reference/std/new/nothrow/
I have a question.
What happens if "Type" is a type whose constructor can throw? In that case, one still needs to handle exceptions in a try/catch block.
So is it a good idea to abandon exception based approach?
I would say that one can use the Abstract Factory/Factory Method design pattern and have all the 'new's in relatively lesser set of files/namespaces/classes, rather than these being scattered all around the place. That may also help in restricting the use of try/catch block to a relatively lesser code.
You can use nothrow keyword with the new operator, which will return NULL rather that throw an exception. For details see link below: http://www.cplusplus.com/reference/std/new/nothrow/
Use nothrow.