Using std::map where V has no usable default constructor

后端 未结 9 1628
予麋鹿
予麋鹿 2020-12-05 13:11

I have a symbol table implemented as a std::map. For the value, there is no way to legitimately construct an instance of the value type via a default constructo

9条回答
  •  遥遥无期
    2020-12-05 13:52

    You can't make the compiler differentiate between the two uses of operator[], because they are the same thing. Operator[] returns a reference, so the assignment version is just assigning to that reference.

    Personally, I never use operator[] for maps for anything but quick and dirty demo code. Use insert() and find() instead. Note that the make_pair() function makes insert easier to use:

    m.insert( make_pair( k, v ) );
    

    In C++11, you can also do

    m.emplace( k, v );
    m.emplace( piecewise_construct, make_tuple(k), make_tuple(the_constructor_arg_of_v) );
    

    even if the copy/move constructor is not supplied.

提交回复
热议问题