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

Discussion in 'C++' started by NewToCPP, Apr 23, 2006.

  1. NewToCPP

    NewToCPP Guest

    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;
    }
     
    NewToCPP, Apr 23, 2006
    #1
    1. Advertisements

  2. Re: How to handle

    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
     
    PasalicZaharije, Apr 23, 2006
    #2
    1. Advertisements

  3. NewToCPP

    Phlip Guest

    NewToCPP wrote:

    > 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.

    --
    Phlip
    http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
     
    Phlip, Apr 23, 2006
    #3
    1. Advertisements

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    5
    Views:
    30,334
    Mike Schilling
    Mar 29, 2006
  2. Pablo J Royo
    Replies:
    7
    Views:
    573
    Jerry Coffin
    Sep 23, 2003
  3. Tim Clacy
    Replies:
    15
    Views:
    3,028
    Kanenas
    May 30, 2005
  4. aneuryzma
    Replies:
    3
    Views:
    978
    Jim Langston
    Jun 16, 2008
  5. Suraj
    Replies:
    4
    Views:
    504
    Suraj
    Apr 7, 2009
  6. jason
    Replies:
    13
    Views:
    1,288
    John B. Matthews
    May 14, 2010
  7. A
    Replies:
    7
    Views:
    804
  8. Christopher
    Replies:
    4
    Views:
    651
    Ruben Safir
    Jul 9, 2011
Loading...