C++ 使用唯一的\u ptr作为值初始化常量静态std::map
这个问题与我的相似。 但在我的问题中,地图应该是只读的。 那么,如何初始化静态常量映射,其中值为std::unique\u ptr:C++ 使用唯一的\u ptr作为值初始化常量静态std::map,c++,C++,这个问题与我的相似。 但在我的问题中,地图应该是只读的。 那么,如何初始化静态常量映射,其中值为std::unique\u ptr: static const std::map 在这种情况下,静态函数内部的初始化不起作用 std::map init() { std::map-mp; mp[0]=std::make_unique(); mp[1]=std::make_unique(); //…等等 返回mp; } 通过初始化列表初始化也不起作用 const std::map={ {0,std:
static const std::map
在这种情况下,静态函数内部的初始化不起作用
std::map init()
{
std::map-mp;
mp[0]=std::make_unique();
mp[1]=std::make_unique();
//…等等
返回mp;
}
通过初始化列表初始化也不起作用
const std::map={
{0,std::make_unique()}
您不能使用std::unique\u ptr
的初始值设定项列表直接实例化常量映射
,因为:
从std::initializer列表构造复制其内容
您不能复制std::unique\u ptr
因此,您可以“动态”创建映射(在函数内部)并将内容移动到常量映射中
即:
using Map = std::map<int, std::unique_ptr<int>>;
static Map GenMap() {
Map m;
m[0] = std::make_unique<int>(0);
// ...
return m;
}
static const Map globalStaticMap = GenMap();
使用Map=std::Map;
静态映射GenMap(){
地图m;
m[0]=std::make_unique(0);
// ...
返回m;
}
静态常量映射globalStaticMap=GenMap();
Lambda可以避免定义静态函数,从而使代码更加紧凑
static const Map globalStaticMap = []() {
Map m;
m[0] = std::make_unique<int>(0);
// ...
return m;
}();
静态常量映射globalStaticMap=[](){
地图m;
m[0]=std::make_unique(0);
// ...
返回m;
}();
您是否尝试过const std::map mp={…}
?首先,您遇到的具体编译错误是什么?其次,请为您的静态常量映射提供动机。使用其他设计模式似乎可以更轻松地满足您的需求。此外,鉴于@felix的评论,我认为您对“通过初始化列表初始化…”。初始化列表需要复制构造,因此无法使用唯一指针。so上存在已知问题。立即调用的lambda的可能副本在这里也很好。