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

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

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

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:
    26,701
    Mike Schilling
    Mar 29, 2006
  2. aneuryzma
    Replies:
    3
    Views:
    717
    Jim Langston
    Jun 16, 2008
  3. jason
    Replies:
    13
    Views:
    883
    John B. Matthews
    May 14, 2010
  4. A
    Replies:
    7
    Views:
    639
  5. Christopher
    Replies:
    4
    Views:
    445
    Ruben Safir
    Jul 9, 2011
Loading...

Share This Page