C++11 lambda 通过引用捕获可平凡破坏

标签 c++ c++11 lambda setjmp

我想知道以下是否泄漏内存(由标准指定)

...
jmp_buf env;
if(setjmp(env) == 0) {
    auto lambda = [&] () {
        ... 
        longjmp(env, 1);
    };
    lambda();
}

这归结为通过引用捕获的 lambda 是否有一个微不足道的析构函数(我猜)?

我知道这可能是邪恶的,但仍然必须这样做。

最佳答案

它是特定于实现的。您可能会合理地期望它是真实的,但标准是这样说的(N4140,[expr.prim.lambda]/3,强调我的):

An implementation may define the closure type differently from what is described below provided this does not alter the observable behavior of the program other than by changing:
— the size and/or alignment of the closure type,
whether the closure type is trivially copyable (Clause 9),
— whether the closure type is a standard-layout class (Clause 9), or
— whether the closure type is a POD class (Clause 9).

根据 [class]/3 中的定义

A trivially copyable class is a class that:
— has no non-trivial copy constructors (12.8),
— has no non-trivial move constructors (12.8),
— has no non-trivial copy assignment operators (13.5.3, 12.8),
— has no non-trivial move assignment operators (13.5.3, 12.8), and
has a trivial destructor (12.4).

因此,允许实现为 lambda 创建一个非平凡的析构函数。

但是,您可以检查您的特定实现是否使您的特定 lambda 可以通过以下方式轻易破坏:

auto lambda = [&]{ /*...*/ };
static_assert(std::is_trivially_destructible<decltype(lambda)>::value, "Lambda isn't trivially destructible");

关于C++11 lambda 通过引用捕获可平凡破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29915596/

相关文章:

c++ - 你应该如何防御?

c++ - 使用 char 或 unsigned char 数组存储原始数据更好吗?

c++ - 如何避免 std::vector 在(重新)分配时复制?

c++ - std::list.sort(Predicate) 编译器错误

c++ - 对另一个类中的一个类使用重载运算符

c++ - 将函数指针实现替换为 std::function 以在 PlayFab SDK 中使用 lambda

c++ - 在 C++ 11 中使用 Homebrew 软件、gcc 和 llvm

c++11 - 基于std::vector的N维张量

python - Pandas - 将列值组合到新列中的列表中

c# - 在 SQL Server 上筛选 Entity Framework 结果