Search code examples
c++stdstdlist

Strange Error regarding using Std::List as a Class Member Variable


I am trying to implement an event handling system in C++ and encountered a compiler error for std::list which I am not able to figure out why.

There is an EventManager class whose role is to manage and fire events. There is a list which stores events to be processed.

If the std::list is declared as a class member, there is an error. Whereas if the list is declared as a local method variable, there is no error.

The class goes like this:

class EventManager
{
   //Queue for events. IEventPtr is a typedef of shared_ptr to an 
   //Events class
   typedef std::list<IEventPtr> EventQueue; 
   EventQueue m_eventQueue;

   virtual bool VQueueEvent(const IEventPtr& pEvent) const;
}

The definition for the VQueueEvent method is:

bool EventManager::VQueueEvent(const IEventPtr& pEvent) const 
{
    //compiler highlighted an error for a class member list
    m_eventQueue.push_back(pEvent);

    //a locally declared list works. No compiler error
    std::list<IEventPtr> eventList;
    eventList.push_back(pEvent);

    return true;
}

From the above code, the compiler underlined the dot notation and had the message "No instance of overloaded function std::list<.....> matches the argument list and object (the object has type qualifiers that prevent a match. Argument types are (const IEventPtr). Object type is const EventManager::EventQueue"

When compiling, the compiler will show the error:

std::list<....>::push_back. 2 overloads have no legal conversion for 'this' pointer

What is causing this error and how to solve it?


Solution

  • The method EventManager::VQueueEvent is marked const. This means it can't modify class members.

    However, the push_back method clearly needs to modify the content of the eventList member, and thus, the error.

    Remove the const qualifier and it should be fine.