By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,191 Members | 1,256 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,191 IT Pros & Developers. It's quick & easy.

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

P: n/a
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::operator[] (unsigned int i)
{
if (period==0)
{
print_error("error");
}

return period[i];
}

Apr 23 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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

Apr 23 '06 #2

P: n/a
NewToCPP wrote:
my_period& my_data::operator[] (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!!!
Apr 23 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.