Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > How to handle "operator []" returning reference to the null pointer

Reply
Thread Tools

How to handle "operator []" returning reference to the null pointer

 
 
NewToCPP
Guest
Posts: n/a
 
      04-23-2006
I have the following code. It complains that there is Possible use of
null pointer. How to handle "operator []" returning reference to the
null pointer?

class my_data
{
private:
my_period* period;

public:
my_period& operator[] (unsigned int);

};


my_period& my_data:perator[] (unsigned int i)
{
if (period==0)
{
print_error("error");
}

return period[i];
}

 
Reply With Quote
 
 
 
 
PasalicZaharije
Guest
Posts: n/a
 
      04-23-2006
Your operator[] can return reference to NULL pointer - try to put

if (period == NULL)
throw ...; // throw something
else return period[i];

Or, just put

return period[i];

without error checking, and make member function
at(int i) that throw exception on out-of-range and
null check (something like C++ libs).

Smarter solution: do not use pointer - use std::vector

 
Reply With Quote
 
 
 
 
Phlip
Guest
Posts: n/a
 
      04-23-2006
NewToCPP wrote:

> my_period& my_data:perator[] (unsigned int i)
> {
> if (period==0)
> {
> print_error("error");
> }
>
> return period[i];
> }


Throw an error. That's how you abort any function which unexpectedly cannot
continue with its normal activity.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
pointer to pointer intialize to NULL but still point to NULL Christopher C++ 4 07-09-2011 12:35 AM
Pointer to pointer or reference to pointer A C++ 7 07-05-2011 07:49 PM
file reader returning null when file is not null content jason Java 13 05-14-2010 01:50 AM
Null pointer (NULL array pointer is passed) aneuryzma C++ 3 06-16-2008 05:48 AM



Advertisments