-11

I tried this:

std::map<int,int> m; 

and it works -- m becomes an empty map. But this approach may not work if the compiler choose to not initialize m to an empty map by default. Better solution?

zell
  • 9,830
  • 10
  • 62
  • 115
  • 8
    This will always make an empty map. That's what map's default constructor does. – NathanOliver Oct 29 '20 at 13:06
  • 6
    if your compiler does not emit code that calls the constructor for `m` then your compiler is broken beyond repair – 463035818_is_not_an_ai Oct 29 '20 at 13:07
  • 1
    You're using the default constructor, so you fall under case "1)" here: https://en.cppreference.com/w/cpp/container/map/map – scohe001 Oct 29 '20 at 13:08
  • If the compiler didn't initialize `m` to an empty map, what would it put in it? – Galik Oct 29 '20 at 13:42
  • 3
    I suspect the reason for so many down votes is that you could have found this out very easily yourself. I suggest referring to cppreference when you have such questions, and you'll see that most answers can be found there :) – cigien Oct 29 '20 at 15:16
  • What makes you think the compiler is going to randomly "choose" how to initialize the map? – Eric Oct 29 '20 at 15:26
  • 1
    @Eric Good question. In C, "int x" may produce different values for x depending on whether x is local, global, and on the compilers , right? But this does not seem to be an obvious question after all, e.g. asking default values of local variables was a question in Java Interview. – zell Oct 29 '20 at 16:50
  • 1
    @zell you are talking about unitialized variables which is undefined behaviour. Objects however are always going to be initialized based on their constructor once you instanciate them. If you dont provide one the compiler will generate the default one for you. – Eric Oct 29 '20 at 19:05
  • @Eric I see! That makes a lot of sense. – zell Nov 02 '20 at 22:32

1 Answers1

8

Any better solution?

Taking your question literally, no. There is no better solution.

This will create a default constructed, and therefore empty std::map<int,int>.

std::map<int,int> m; 
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180