簡體   English   中英

將unique_ptr的映射移到unique_ptr的const映射中

[英]moving a map of unique_ptr into a const map of unique_ptr

我了解以下示例有效:

#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());
}

但是,如果我要強制將smallMap_設為

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

請幫忙,我嘗試了所有已知的舉動組合。

做就是了

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

現場例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM