c++ - Equality operator (==) unsupported on map iterators for non-copyable maps -
when have map of non-copyable objects, why can't compare iterators using ==? imagine not need copy (or move) actual objects when doing equality testing on iterators.
#include <iostream> #include <utility> #include <map> using namespace std; class { private: int i; public: a(int i) : i(i) {} a(a&) = delete; a(a&& a) : i(a.i) {} ~a() {} a& operator=(a&) = delete; bool operator==(const a& a) const { return == a.i; } }; int main() { map<int, a> mymap; map<int, a>::iterator = mymap.find(1); cout << (it == mymap.end()) << endl; } this example fails compile, giving error on line cout.
g++ gives error:
/usr/include/c++/4.8.2/bits/stl_pair.h: in instantiation of ‘struct std::pair<const int, a>’: test2.cpp:24:27: required here /usr/include/c++/4.8.2/bits/stl_pair.h:127:17: error: ‘constexpr std::pair<_t1, _t2>::pair(const std::pair<_t1, _t2>&) [with _t1 = const int; _t2 = a]’ declared take const reference, implicit declaration take non-const constexpr pair(const pair&) = default; clang++ gives error:
/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../include/c++/4.8.2/bits/stl_pair.h:127:17: error: parameter explicitly-defaulted copy constructor const, member or base requires non-const constexpr pair(const pair&) = default; ^ test2.cpp:24:14: note: in instantiation of template class 'std::pair<const int, a>' requested here cout << (it == mymap.end()) << endl; however, work if map<int, int> used instead of map<int, a>. using const map<int, a> map<int, a>::const_iterator not help.
i tried looking exact signature of map::iterator::operator== on cppreference, (map::iterator bidirectionaliterator, forwarditerator, inputiterator) website vague exact type signatures in concepts.
the problem deleted methods make noncopyable ...
#include <iostream> #include <utility> #include <map> using namespace std; class { private: int i; public: a(int i) : i(i) {} // a(a&) = delete; should ... a(const a&) = delete; a(a&& a) : i(a.i) {} ~a() {} // a& operator=(a&) = delete; should ... a& operator=(const a&) = delete; bool operator==(const a& a) const { return == a.i; } }; int main() { map<int, a> mymap; map<int, a>::iterator = mymap.find(1); cout << (it == mymap.end()) << endl; } verified gcc/g++ 4.6.3
removing "const" copy constructor , assignment operator caused compiler give same error received.
i have details/references why declared way, copy constructor , assignment operator take const reference (make sense value instance being assigned should not modified method).
Comments
Post a Comment