Reference as key in std::map

后端 未结 4 764
傲寒
傲寒 2021-02-07 12:39

Suppose some data structure:

typedef struct {
    std::string s;
    int i;
} data;

If I use the field data.s as key when adding i

4条回答
  •  广开言路
    2021-02-07 13:16

    You cannot use the reference. The map can copy the content. This is I guess implementation dependent.

    But tested with the microsoft STL.

    struct data
    {
                data(data const& rhs)
                {
                   a new object will be created here
                }
                std::string s;
                int i; 
    };
    

    Add some objects to the map and you will run into the copy constructor. This should invalidate your reference.

提交回复
热议问题