Domanda

I'm working with C++ queues. First, I make a push (the copy constructor is called and works fine) and when I do a simple pop, it calls the first destructor method (not the new created). Here a sample code:

{
    T_MENSAJE new_msg;      // Constructor 1 called -> Instance 1

    new_msg.rellena(msg);

    m_messages.push(new_msg);   // Copy constructor called -> Instance 2

    m_messages.pop();       // Destructor of instance 1 called !!!!!!!

    return;             // again, destructor of instance 1 called
}

Edit:

For demonstrate it, I show the memory direction of m_data, into rellena(msg); constructor copy method and in the destroyer. In rellena, has memDir1, in copy constructor memDir2, as I expectyed. But when I call pop method, the destroyer method shows memDir1 (not memDir2 as I expected), then when the function finish, the destroyer is called again and memDir1 is shown again. Here is the T_MENSAJE struct:

typedef struct T_MENSAJE
{
    T_MSG_HEADER m_cab;
    char        m_command[MSG_COMMAND_SIZE];
    char*       m_data;

    T_MENSAJE():m_data(0){
    }

    ~T_MENSAJE()
    {
        static int counter = 0;
        if (m_data != 0)
        {
            printf("%s -- direction = %d\n",__FUNCTION__,m_data);
            delete[](m_data);
        }
    }

    T_MENSAJE(const T_MENSAJE& m)
    {

        m_cab = m.m_cab;
        memcpy(&m_command,&m.m_command,MSG_COMMAND_SIZE);

        if (m.m_data != 0)
        {
            int numBytes = m_cab.m_lenght-MSG_HEADER_SIZE-MSG_COMMAND_SIZE;
            m_data = new char[numBytes];
            printf("%s -- direction = %d\n",__FUNCTION__,m_data);
            memcpy((char*)&(m_data),&m.m_data, numBytes);
        }else
        {
            m_data = 0;
        }

    }

......
......
......
}
È stato utile?

Soluzione

The memcpy memcpy((char*)&(m_data),&m.m_data, numBytes); copies numBytes from the address of &m.m_data to the address of your member m_data. This is wrong and overwrites parts of your object.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top