简体   繁体   中英

moving a map of unique_ptr into a const map of unique_ptr

I understand that the following example works:

#include <memory>
#include <map>

using namespace std;

map<int, unique_ptr<int> > mapCreator () {
  map<int, unique_ptr<int> > smallMap;
  for (int i = 0; i < 10; i++) {
    unique_ptr<int> ptr(new int(10));
    smallMap.insert(make_pair(
      i,
      std::move(ptr)
    ));
  }
  return smallMap;
};

class mapContainer {
 public:
  mapContainer(map<int, unique_ptr<int> > smallMap) {
    std::move(smallMap.begin(), smallMap.end(), std::inserter(smallMap_, smallMap_.begin()));
  }     
 private:
  map<int, unique_ptr<int> > smallMap_;
};

int main() {
  mapContainer container(mapCreator());
}

however, what do I do if I want to force smallMap_ to be

const map<int, unique_ptr<int> > smallMap_;

Please help, I have tried all the move combinations I know of.

Just do

class mapContainer
{
public:
    mapContainer(map<int, unique_ptr<int> > smallMap) :
        smallMap_(std::move(smallMap))
    {
    }
 private:
    const map<int, unique_ptr<int> > smallMap_;
};

Live example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM