c++ - 声明 lambda 然后立即调用以使用其返回值初始化局部变量是否有任何目的?
问题描述
template<typename T>
static const Metatype* get_metatype() {
static const Metatype* mt = []() {
constexpr size_t name_hash = Metatype::build_hash<T>().name_hash;
auto type = metatype_cache.find(name_hash);
if (type == metatype_cache.end()) {
constexpr Metatype newtype = Metatype::build<T>();
metatype_cache[name_hash] = newtype;
}
return &metatype_cache[name_hash];
}();
return mt;
}
由 lambda 的返回值初始化的变量mt 。为什么不直接提取 lambda 代码并使其成为 get_metatype() 函数的一部分,然后只从中返回值呢?这是一些表演技巧还是什么?
此代码来自我正在为教育目的学习的decs https://github.com/vblanco20-1/decs项目。
解决方案
这通常用于初始化需要为 的变量const
,但初始化起来也很复杂。例如
const std::vector<int> v = [] {
std::vector<int> vv;
// ... very complicated logic to initialize vv
// even could be IO, etc ...
return vv;
}();
不这样做,就没有好的方法来制作v
const
.
但是,在您的情况下,在提供的示例中使用此技术的原因是,如@walnut 和@Remylebeau 所指出的,mt
每次调用时都不会初始化静态变量。get_metatype
推荐阅读
- python - 计算账户金额的问题 Python
- asp.net - 能够通过 ASPX 母版页中的菜单下拉列表滚动
- java - 如何使用谓词构建器返回“今日订单”
- c# - Asp.net MVC Booked StartDate 和 EndDate 检查
- javascript - 使用 Leaflet 为 GeometryCollection 类型的几何设置样式
- android - 将 Android 深度相机流 (DEPTH16) 捕获为 OpenGL ES 纹理
- swift - 如何使用 Alamofire + RxSwift 同步刷新访问令牌
- php - 如何使用 php://fd/ 包装器?
- html - 无法向下滚动查看我的 html 文件的其他内容
- android - 在主要活动中从一个片段切换到另一个片段