C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

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

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++)
View previous topic :: View next topic  
Author Message
NewToCPP
Guest





PostPosted: Sun Apr 23, 2006 9:06 pm    Post subject: How to handle "operator []" returning reference to the null Reply with quote



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





PostPosted: Sun Apr 23, 2006 10:06 pm    Post subject: Re: How to handle "operator []" returning reference to the n Reply with quote



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





PostPosted: Sun Apr 23, 2006 10:06 pm    Post subject: Re: How to handle Reply with quote



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
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++) All times are GMT
Page 1 of 1

 
 


Powered by phpBB © 2001, 2006 phpBB Group