user3081218
user3081218

Reputation: 79

unordered_map emplace - how to create objects in place

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>{});
}

Upvotes: 3

Views: 2936

Answers (2)

Roman Kruglov
Roman Kruglov

Reputation: 3547

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.

Upvotes: -1

Kerrek SB
Kerrek SB

Reputation: 477444

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.)

Upvotes: 5

Related Questions