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

后端 未结 9 1571
予麋鹿
予麋鹿 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:45

    Derive a new class from std::map<K,V> and create your own operator[]. Have it return a const reference, which can't be used as an l-value.

    0 讨论(0)
  • 2020-12-05 13:48

    Not sure why it compiles for you, I think the compiler should have caught your missing constructor.

    what about using

    map<K,V*>
    

    instead of

    map<K,V> ?
    
    0 讨论(0)
  • 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.

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