c++ - Cannot iterate over map whose elements hold a uniq_ptr -


the following code fails compile:

#include <iostream> #include <memory> #include <map>  struct haveuniq {     std::unique_ptr<int> uniq; };  void print_hus(const std::map<int, haveuniq>& hus) {     (const std::pair<int, haveuniq>& p: hus)         std::cout << *p.second.uniq << std::endl; }  int main() {     std::map<int, haveuniq> hus;     (int = 0; < 10; ++i)         hus[i].uniq = std::unique_ptr<int>(new int(i));     print_hus(hus); } 

with following error:

uniq_wtf.cpp: in function ‘void print_hus(const std::map<int, haveuniq>&)’: uniq_wtf.cpp:10:42: error: invalid initialization of reference of type  ‘const std::pair<int, haveuniq>&’ expression of type ‘const std::pair<const int, haveuniq>’ (const std::pair<int, haveuniq>& p: hus) 

so, tries iterate on values rather constant references, , cannot coerce values references.

it clear objects has unique_ptr 1 of fields cannot have default copying constructor. if understand correctly, iterating on map doesn't involve copying, shouldn't problem. or map iterator copy values? , why have problem coercing values references?

by way, code works if unique_ptr replaced simple integer, , if map replaced std::array.

compiler error clear. std::map::value_type std::pair<const key, value>, make code works:

for (const std::pair<const int, haveuniq>& p: hus) 

or just

for (const auto& p : hus) 

live example


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -