0

I have a unordered map with an enum in key and a shared_ptr in content.

When I initialize my map, I use emplace like this :

this->_menu.emplace(BINDINGS, std::shared_ptr<AMenu>(new BindingMenu("Player 1"));

But I would like to know if I can replace (at the same place), with another BindingMenu object :

std::shared_ptr<AMenu>(new BindingMenu("Player 2")

Thanks

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 1
    `this->_menu[BINDINGS] = std::make_shared("Player 2");` ? – Jarod42 Jun 01 '17 at 12:16
  • Have you tried? –  Jun 01 '17 at 12:19
  • Don't begin identifiers with underscores. If you want to distinguish members from locals or parameters then use `m_menu` or `mMenu`. Use of `this` is optional except when accessing members of a templated base class. Use `std::make_shared("Player 2");` to create a `std::shared_ptr` – Indiana Kernick Jun 01 '17 at 12:26
  • Why it's better with "m" before ? for "member" ? – Paul Julien Jun 01 '17 at 12:48
  • Yes, "m" is for "member". You don't have to prepend "m" but it's a common convention among C++ developers. – Indiana Kernick Jun 01 '17 at 13:16
  • The underscore as prefix is to avoid to break those rules [what-are-the-rules-about-using-an-underscore-in-a-c-identifier](https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier). – Jarod42 Jun 01 '17 at 13:37
  • You need to delete the old value or you will leak. – stark Jun 01 '17 at 15:03
  • @stark: auto-magically done thanks to smart pointer. – Jarod42 Jun 01 '17 at 17:36

1 Answers1

0

As @Jarod42 mentioned, you can access an element in a map using the operator[]

this->_menu[BINDINGS] = std::shared_ptr<AMenu>(new BindingMenu("Player 2"));

If the element you are trying to access didn't exist yet, it will be created.

More information here http://www.cplusplus.com/reference/unordered_map/unordered_map/operator[]/

jbalestr42
  • 74
  • 1
  • 6