lundi 15 mars 2021

Unique_ptr on stack becomes pointer to self ater move() into function

Im trying to pass unique_ptr into function in this code.

    unique_ptr<Message> msg = nullptr;
    
    if(handle == board_->handle())      { msg = board_->TryGet();   }
    
    if(msg) switch(msg->dest){ default: break; // LOG NEEDED
        case Module::DATABASE:  
            database_.HandleMessage(move(msg)); 
            break;
    }

// Somewhere far
    bool HandleMessage(unique_ptr<Message> received)
    {
        
    }

When msg was auto

auto msg = board_->TryGet();

It works fine, but now, received in HandleMessage(move(msg)) has value equals to address of stack variable msg.

It may hard to understand, i try in pseudocode

unique_ptr<Message> msg = unique_ptr<Message>(0x01);
auto msg_ptr = &msg; 
assert(msg_ptr == 0x02);
HandleMessage(move(msg));

void HandleMessage(unique_ptr<Message> received)
{
    assert(received.get() == 0x02);
}

Aucun commentaire:

Enregistrer un commentaire