-1

I am trying to figure out a way to get a thread out of an unordered_map in c++.

However, I am getting the std::thread::thread(const std::thread &) attempting to reference a deleted function.

Example:

#include "stdafx.h"
#include <unordered_map>
#include <thread>

class ThreadContainer
{
    std::unordered_map<int, std::thread> map_;
public:
    void addThread(int handle, std::thread thread)
    {
        map_.emplace(std::move(handle), std::move(thread));
    }

    std::thread getThread(int handle)
    {
        return map_.at(handle);
    }
};

int main()
{
    ThreadContainer testing;

    return 0;
}

In this code example I have tried return map_.at(handle); and return std::move(map_.at(handle); neither of these seem to work.

How can I get the std::thread back out of this unordered_map?

Questionable
  • 768
  • 5
  • 26
  • 1
    _"I'm guessing..."_ Your guess is wrong. _"If that is true..."_ That is not true. What is your real question? What are you trying to ask? – Drew Dormann Feb 27 '18 at 22:35

1 Answers1

2
std::thread getThread(int handle)

is a function that returns by value. This requires a non-deleted copy constructor. As you've noted, std::thread's copy constructor has been deleted.

Solution: Return by reference

std::thread & getThread(int handle)

and make sure the receiver is also a reference. Do not force copying at any point in the chain.

If by "get the std::thread back out of this unordered_map" you want to remove the thread from ThreadContainer you could

std::thread&& removethread(int handle)
{
    return std::move(map_.at(handle));
}

but this will leave a "dead" thread in map_. You will probably want to remove the key and the now-unattached thread.

std::thread&& removethread(int handle)
{
    std::thread temp(std::move(map_.at(handle)));
    map_.erase(handle);
    return std::move(temp);
}

Also note that ThreadContainer will not be copyable because the contained threads cannot be copied. You will get much more readable error messages if you delete ThreadContainer's copy constructor and assignment operator.

user4581301
  • 33,082
  • 7
  • 33
  • 54