Why a default constructor is needed using unordered_map and tuple?

前端 未结 1 725
日久生厌
日久生厌 2021-01-05 03:59

In the program below, I store some information in an hash table (std::unordered_map), the key is an object of the class RectData, the associated value is a tuple

相关标签:
1条回答
  • 2021-01-05 04:35
    visited_info[rect0] = info0;
    

    well, what do you think this does? It's well-documented that the left-hand side evaluates to a reference to an item stored in the map. If that item wasn't there before, it is default constructed first.

    You then use either copy- or move-assignment to update that default-constructed item from the right-hand-side of the expression.

    If you want to avoid the default-construct-and-assign operation you're getting now, use emplace instead.


    NB. One possible source of confusion is, for example, Python, where MyObj[1] might translate to a __getitem__ call, but MyObj[1]=1 to a __setitem__ call.

    In C++, both the left-hand-side and right-hand-side expressions must evaluate to something, without knowing anything about the statement they're in. Hence, the left-hand-side evaluates to a reference which you can either read from or assign to - but the object needs to exist before you can take that reference.

    0 讨论(0)
提交回复
热议问题