mercredi 6 novembre 2019

Modifications to data members do not persist after function ends

I've got a simple hierarchy which consists of an Agent that has a ConversationManager con_manager* data member that handles an arbitrary amount of Conversations in a std::vector<Conversation> conversations which themselves contain 1-5 Messages in a std::Vector<Message> messages .

If I start a Conversation via

ConversationManager::startConversation(Message &message) {
    Conversation conversation = Conversation(message);
    conversations.push_back(conversation)
}

The message is saved properly. But after adding messages via

int ConversationManager::addMessage(Message &message){
    if(conversations.size() > 0){
        Conversation conversation = conversations.back();
        conversation.addMessage(message);
        return 0;
    }
    return -1;
}

and

int Conversation::addMessage(Message &message){
    …
    messages.push_back(message);
    …
}

subsequent messages besides the first one are not saved. Printing the size and content of messages in Conversation::addMessage(Message &message)shows that my message is saved within that function, but seems to get lost when the scope of the function ends. To my understanding, an explanation would be that the conversation objects used in ConversationManager::addMessage(Message &message) is merely a copy and thus modifications are not saved. But std::Vector::back() returns a reference, so this should be impossible.

I tried only having a single Conversation object without the ConversationManager and then messages are permanently saved. I have a feeling that the Problem lies in my misunderstanding of reference usage. I don't think more code is needed for understanding, but I can provide it if someone thinks it's needed. Any help as to why this occurs would be appreciated, I think I'm making a fundamental mistake here but can't get out of the "This shouldn't be happening"-mindset.

Aucun commentaire:

Enregistrer un commentaire