 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
NewToCPP Guest
|
Posted: Sun Apr 23, 2006 9:06 pm Post subject: How to handle "operator []" returning reference to the null |
|
|
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];
} |
|
| Back to top |
|
 |
Phlip Guest
|
Posted: Sun Apr 23, 2006 10:06 pm Post subject: Re: How to handle "operator []" returning reference to the n |
|
|
NewToCPP wrote:
| Quote: | 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!!! |
|
| Back to top |
|
 |
PasalicZaharije Guest
|
Posted: Sun Apr 23, 2006 10:06 pm Post subject: Re: How to handle |
|
|
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 |
|
| Back to top |
|
 |
Powered by phpBB © 2001, 2006 phpBB Group
|