Boost logo

Boost Users :

From: Nikolai N Fetissov (nikolai-boost_at_[hidden])
Date: 2008-07-15 09:59:20


> Marshall Clow (14.7.2008 23:50):
>> At 4:43 PM -0500 7/14/08, Meryl Silverburgh wrote:
>>> Hi,
>>>
>>> Can you please tell me how can I return a 'null' smart pointer?
>>>
>>> typedef shared_ptr<MyA> MyAPtr;
>>> typedef vector<MyAPtr> MyAVector;
>>>
>>> For example,I have this code, which return NULL in an error situation:
>>>
>>> MyAPtr myfunction(MyAVector& v, int size) {
>>> if (index < v.size()) {
>>> return v[index];
>>> } else {
>>> // how can I return NULL here?
>>> }
>>> }
>>>
>>> How can I achieve that when I use boost smart pointer?
>>
>> I suggest that you throw an exception here, rather than returning some
>> bogus value.
>
> What is so bad in general about returning uninitialized smart pointers?
> Is that more costly than throwing an exception? I mean, there is even
> some support for testing a smart pointer for validity built into
> shared_ptr, so why not use it where appropriate?
>

The only problem with returning a null pointer, or -1,
or whatever in case of error is that it's easy to ignore
at the calling scope, so the upper layers would not even know
the error occurred. Exception, on the other hand, propagates
up the stack enforcing more structured error handling.

--
 Nikolai

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net