STL map insertion efficiency: [] vs. insert

前端 未结 6 1684
走了就别回头了
走了就别回头了 2021-02-12 22:23

There are two ways of map insertion:

m[key] = val;

Or

m.insert(make_pair(key, val));

My question is, which op

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-12 22:56

    My answer is not on efficiency but on safety, which is relevant to choosing an insertion algorithm:

    The [] and insert() calls would trigger destructors of the elements. This may have dangerous side effects if, say, your destructors have critical behaviors inside.

    After such a hazard, I stopped relying on STL's implicit lazy insertion features and always use explicit checks if my objects have behaviors in their ctors/dtors.

    See this question: Destructor called on object when adding it to std::list

提交回复
热议问题