views:

102

answers:

2

This is a snippet of code I use:

void Move::AddToMovesList(Location* &list, int row, int col) {
    // If the list is empty, create the first item
    if (list == NULL)
        list = new Location(row, col);
    // List exists, so append
    else
        list->Add(row, col);
}

If list is NULL, a new Location should be created and the pointer list should point to that new location. That's the behavior I'd expect from this code, but right before gdb exits this function I noticed that list is still NULL. What am I doing wrong here?

I used the ampersand in Location* &list to make sure that I can permanently (vs. locally) change the supplied pointer.

A: 

Personally I would not use pointer at all.

class Location
{
    public:
        void add(int row, int col)
        {
            data.push_back(std::make_pair(row,col));
        }
        bool isEmpty()  const {return data.empty(); }
    private:
        std::vector<std::pair<int,int> > data;
};


class Move
{
    public:
        // Pass a reference to the list.
        // No special case processing if the list is empty.
        // No problems with ownership.
        // No problems with lifespan associated with new/delete
        void addToMoveList(Location& list, int row, int col)
        {
            list.add(row, col);
        }
};

int main()
{
    Location    list;  // Don't use new if you can declare a local variable.
    Move        move;

    move.addToMoveList(list, 10, 2);
}
Martin York
Looks much easier to implement, but as I mentioned in another comment I'm doing a school project on C++ and we've hardly covered any C++-specific advantages. I'm not allowed to use stuff we haven't covered in the project, so for now I think I have to stick to the C alternative of creating dynamically linked lists.
Pieter
@Pieter - you may not be allowed to use STL etc, but still you don't have to do it in C fashion, with brute-force memory management via new/delete/malloc/free and raw pointers everywhere.
Steve Townsend
+1  A: 

Let's not reinvent the wheel here... Know your libraries.

If you use the STL list container (or any other container) then you don't need to bother with null pointers.

Platinum Azure
I'm doing this for a school project and we've not covered lists in our C++ course so far, so unfortunately I'm not allowed to use them.
Pieter