Search code examples
heap-memorymoveunordered-mapstack-memoryraii

std::move() a stack allocated unordered_map?


I was just wondering if it was sensible to create a task-local unordered_map that I later move to global space like this:

void StatesRegister(std::vector<global_states_t>states)
{
    // create temporary notify map
    local_map tmp_map;

    // fill map...

    // move to global task map
    TaskHandle_t handle = (void*)0x50;

    // MUTEX
    // emplace to global map
    task_map.emplace(handle, std::move(tmp_map));
    // /MUTEX
}

The question is whether or not I can use std::move here... Afaik an unordered_map is a RAII-object, so while the object is "hosted" on the taskstack, buckets are kept on the heap. So my hope is that the move-constructor of std::unordered_map will understand what I'm trying to do and just pass over buckets to the newly created instance on the heap, but will it?


Solution

  • Your expectation and code are fine - you can move-assign to a variable elsewhere in your program from your local variable (tmp_map). More generally, there's more to an unordered_map than just "buckets" - the buckets typically contain iterators to forward list nodes per stored element. Regardless, ownership of all the existing elements and the buckets/nodes related to them will be transferred to the move-assigned-to variable. You should of course ensure that any other thread accessing the move-assigned-to variable locks the mutex similarly.