C 11 lambdas通过参考捕获可以轻微破坏

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

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

归结为lambdas通过引用捕获是否有一个简单的析构函数(我猜)?

我知道这可能是邪恶的,但不过必须这样做.

最佳答案
它是特定于实现的.你可以合理地期望它是真的,但这是标准所说的(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 lambdas通过参考捕获可以轻微破坏 - 代码日志