我想知道以下是否泄漏内存(由标准指定)
...
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/