Assignment in C++ occurs despite exception on the right side

前端 未结 3 1322
遥遥无期
遥遥无期 2021-02-03 17:05

I have some (C++14) code that looks like this:

map> junk;
for (int id : GenerateIds()) {
    try {
        set stuff =         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-02-03 17:09

    You're misunderstanding how operator[] works on std::map.

    It returns a reference to the mapped item. Therefore, your code is first inserting a default item in that position and then invoking operator= to set a new value.

    To make this work the way you expect, you'll need to use std::map::insert (*):

    junk.insert(std::make_pair(id, GetStuff()));
    

    Caveat: insert will only add the value if id is not already mapped.

提交回复
热议问题