-1

I need to find a way to accomplish what I want below, described in the comments. I am trying to use unique_ptr to do so but not having access to make_ptr I'm at a loss. I'd like to use STL's automatic heap allocators and such for this. I just want the map to be able to have itself as a value, by hook or crook. Since I'm targeting the Arduino SDK (but for 32-bit cpus) I don't think I can use boost based solutions nor use C++14.

#include <memory>
#include <string>
#include <unordered_map>
struct map_value;
struct map_value {
  // what I *really* want - works with std::map on GCC i guess
  //std::unordered_map<std::string,map_value> value;
  
  // what I'll settle for
  std::unordered_map<std::string,std::unique_ptr<map_value>> value;
};
void setup() {
  
  map_value mv;
  map_value* pmv2 = new map_value();
  // what sorcery do i use below? i don't have std::make_unique nor can I get it 
  mv.value.insert(std::make_pair("test",pmv2));
}

void loop() {
}

I'll take any alternative that gets me what I want.

Thanks in advance. Sorry if this has been asked before. I looked and could only find solutions involving unique_ptr/make_unique

  • What do you mean by *I just want the map to be able to have itself as a value*? Can you explain that a little more? – NathanOliver Dec 10 '20 at 16:55
  • Your example seems to compile fine. What's the problem? – Aykhan Hagverdili Dec 10 '20 at 17:02
  • NathanOliver, I put a comment in the code as to what I want: std::unordered_map value, like that – honey the codewitch Dec 10 '20 at 17:14
  • Ayxan I think you're using a newer compiler than me. I cannot use the latest C++ features - I get: no matching function for call to 'std::unordered_map, std::unique_ptr >::insert(std::pair) – honey the codewitch Dec 10 '20 at 17:14
  • Try `mv.value.insert(std::make_pair("test",std::unique_ptr(pmv2)))`. `std::make_unique` is really simply... dynamic allocation (with `new`) following by constructing a `std::unique_ptr` to hold the pointer. The constructor is explicit so it won't convert from raw pointer to `unique_ptr` automatically, you have to ask it. – Ben Voigt Dec 10 '20 at 17:19
  • Not exactly a dupe of https://stackoverflow.com/questions/13089388/how-to-have-an-unordered-map-where-the-value-type-is-the-class-its-in?noredirect=1&lq=1 (it explains why you need to "settle for" unique_ptr), definitely related so putting back the link to that question. – Ben Voigt Dec 10 '20 at 17:22
  • Thank you Ben, that solved it for me. I seem to remember trying that but apparently i didn't. :) – honey the codewitch Dec 10 '20 at 17:24

1 Answers1

0

Try mv.value.insert(std::make_pair("test",std::unique_ptr<map_value>(pmv2))). std::make_unique is really simply... dynamic allocation (with new) following by constructing a std::unique_ptr to hold the pointer. The constructor is explicit so it won't convert from raw pointer to unique_ptr automatically, you have to ask it.

– Ben Voigt

Thank you Ben. That did it for me.