Lambda 捕获条款的问题
Issue with Lambda's capture clause
我正在尝试使用 ftw 函数来计算目录的大小。ftw 函数的原型是:
int ftw(const char *dirpath,
int (*fn) (const char *fpath, const struct stat *sb,
int typeflag),
int nopenfd);
为了计算整个目录的大小,我尝试使用 lambda 表达式使用以下代码:
uint32_t calcDirSize(const char *path) {
uint32_t usize = 0;
if (ftw(path, [&usize](const char *fpath, const struct stat *sb, int typeflag) {
usize += sb->st_size;
return 0;
}, 1)) {
return 0;
}
return usize;
}
它为 lambda 表达式的捕获子句中的变量抛出错误。我想使用局部变量来计算大小,并在计算后从 calcDirSize 函数返回。 有没有其他方法可以达到相同的结果?
lambda 只有在无状态或换句话说不捕获任何内容时才可转换为函数指针。
仅当变量具有静态存储持续时间时,您才可以在没有捕获的情况下使用 lambda 外部的变量。
uint32_t calcDirSize(const char *path) {
static uint32_t usize = 0;
usize = 0; // Make sure it's reset to 0 every time the function is called.
if (ftw(path, [](const char *fpath, const struct stat *sb, int typeflag) {
usize += sb->st_size;
return 0;
}, 1)) {
return 0;
}
return usize;
}
通过使usize
静态,我们可以删除lambda中的捕获,这使得它可以转换为函数指针。
编辑:如注释中所述,这不是线程安全的,因为对calcDirSize
的多次调用可以同时修改/读取usize
。
相关文章:
- Lambda 捕获条款的问题
- 在使用 std::sort() 和 lambda 函数按属性对 ADT 的向量进行排序时遇到问题
- 与lambda一起使用虚拟继承在初始化列表中捕获此问题的GCC错误
- 关于Lambda超载,输入转换和完美转发的问题
- lambda函数的C++问题
- 这种递归多态 C++1y lambda 调用有什么问题?
- C++Lambda函数关闭-内存问题
- 使用C++11 lambda函数将点击事件连接到函数时出现问题
- 我的 lambda 表达式进行映射键比较有什么问题?
- 奇怪的lambda问题(编译器错误?
- 在 C++ 中使用 Lambda 表达式和 auto 关键字时出现问题
- 将 lambda 转换为 std::函数时出现问题
- 嵌套Lambda捕获问题
- C++:lambda函数和捕获列表的问题
- std::find中的Lambda问题
- C++boost lambda和===-运算符的问题
- 使用std::bind在lambda中捕获std::unique_ptr时出现问题
- 将lambda传递给模板类中的方法(头文件/源文件问题)
- 这种使用 boost::lambda::bind 有什么问题?
- 模板化函数接受lambda问题