Keselme
Keselme

Reputation: 4249

Problem with passing list pointer to a function

In my program I have a list which is a pointer list<COffenceUnit*>* m_attack = nullptr; I initialize this list like that: m_attack = new list<COffenceUnit*>(); in the constructor. At some point in the code I want to send this list to another constructor as a reference. This is the constructor that receives the list:

GameMap::GameMap(const std::list<CDefenceUnit*>* &defenseUnits, const std::list<COffenceUnit*>* &offenseUnits)
{
    mGameMap = new int* [GRID_SIZE];
    for (int i = 0; i < GRID_SIZE; ++i)
        mGameMap[i] = new int[GRID_SIZE];

    updateMap(defenseUnits, offenseUnits);
}

However the compiler throws an error that says:

Error   C2664   'GameMap::GameMap(const GameMap &)': cannot convert argument 1 from
'std::list<CDefenceUnit *,std::allocator<_Ty>> **' to 'const std::list<CDefenceUnit *,std::allocator<_Ty>> *&'

I can't figure out what am I doing wrong here.

Upvotes: 0

Views: 75

Answers (1)

Emil Laine
Emil Laine

Reputation: 42838

You're trying to call the function with a pointer-to-pointer-to-list (std::list<...>**), but the function expects a pointer-to-list (std::list<...>*), so the conversion fails.

Dereference the argument to remove one level of pointer. For example if you had GameMap(defenseUnits), then change that to GameMap(*defenseUnits).


Also you should almost never new std containers, so to initialize your m_attack, it's recommended to do it without new (i.e. without dynamic allocation), like so:

list<COffenceUnit*> m_attack;

Then you also don't need to do m_attack = list<COffenceUnit*>(); later, because the list is already default initialized by the list's constructor.

This also helps you avoid multiple levels of pointers, such as in std::list<...>**.


Also you probably want std::vector instead of std::list, the latter is rarely a better choice.

Upvotes: 1

Related Questions