Non-static const member, can't use default assignment operator

后端 未结 4 1653
北海茫月
北海茫月 2020-11-27 04:45

A program I\'m expanding uses std::pair<> a lot.

There is a point in my code at which the compiler throws a rather large:

N

4条回答
  •  孤街浪徒
    2020-11-27 05:40

    You have a case like this:

    struct sample {
        int const a; // const!
    
        sample(int a):a(a) { }
    };
    

    Now, you use that in some context that requires sample to be assignable - possible in a container (like a map, vector or something else). This will fail, because the implicitly defined copy assignment operator does something along this line:

    // pseudo code, for illustration
    a = other.a;
    

    But a is const!. You have to make it non-const. It doesn't hurt because as long as you don't change it, it's still logically const :) You could fix the problem by introducing a suitable operator= too, making the compiler not define one implicitly. But that's bad because you will not be able to change your const member. Thus, having an operator=, but still not assignable! (because the copy and the assigned value are not identical!):

    struct sample {
        int const a; // const!
    
        sample(int a):a(a) { }
    
        // bad!
        sample & operator=(sample const&) { }
    };
    

    However in your case, the apparent problem apparently lies within std::pair. Remember that a std::map is sorted on the keys it contains. Because of that, you cannot change its keys, because that could easily render the state of a map invalid. Because of that, the following holds:

    typedef std::map map;
    map::value_type <=> std::pair
    

    That is, it forbids changing its keys that it contains! So if you do

    *mymap.begin() = make_pair(anotherKey, anotherValue);
    

    The map throws an error at you, because in the pair of some value stored in the map, the ::first member has a const qualified type!

提交回复
热议问题