3

need to create unordered_map for integer and some user defined class - MyClass, where MyClass uses mutex for data access synchronisation, i.e. MyClass object can not be copied or moved. Is it possible to create such a map? How do I use emplace to create object of MyClass to avoid copy/move?

template<typename T>
class MyClass {
  public:
    T pop() {
      std::unique_lock<std::mutex> lock(m_mutex);
      m_cv.wait(lock, [this]{return !m_queue.empty();});
      return m_queue.pop();
    }
    void push(T const& x) {
      { 
        std::unique_lock<std::mutex> lock(m_mutex);
        m_queue.push(x) ;
      }
      m_cv.notify_one();
    }
  private:
    std::queue<T> m_queue ;
    std::mutex m_mutex ;
    std::condition_variable m_cv;
};

int main(){
  std::unordered_map<int, MyClass<float>> mmap;
  mmap.emplace(1, MyClass<float>{});
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
user3081218
  • 79
  • 2
  • 7
  • anyway this code will not compile, as `std::queue::pop` returns void, and not `T`. if `T` is `void`, than `std::queue` is illegal – David Haim Feb 22 '17 at 12:56

2 Answers2

5

You need:

mmap.emplace(std::piecewise_construct,
             std::forward_as_tuple(1),  // args for key
             std::forward_as_tuple());  // args for mapped value

(This uses the piecewise pair constructor for the value type.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
-1

TL;DR: just use operator [], I think it's simpler, like:

std::map<int, MyClass<float>> mmap;
auto& obj = mmap[1]; // here it created an object and returned a reference

Details: I had a similar situation once, here is a link to my answer with details.

Roman Kruglov
  • 3,375
  • 2
  • 40
  • 46