Lambda 捕获条款的问题

Issue with Lambda's capture clause

本文关键字:问题 Lambda      更新时间:2023-10-16

我正在尝试使用 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