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

N

NewToCPP

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::eek:perator[] (unsigned int i)
{
if (period==0)
{
print_error("error");
}

return period;
}
 
P

PasalicZaharije

Your operator[] can return reference to NULL pointer - try to put

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

Or, just put

return period;

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
 
P

Phlip

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

return period;
}


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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top