This code prints 0 or 666 when built with clang++ -std=c++11, depending on the optimization level (-O3 yields 666, which is what I would expect). When lambda is passed by universal reference the problem disappears.
FYI, GCC prints 666 on all the versions I've tested.
Is it a compiler bug or the code is incorrect?
template <typename T>
std::shared_ptr<void> onScopeExit(T f)
{
return std::shared_ptr<void>((void*)1, [&](void *) {
f();
});
}
struct A {
void f() {
auto scopeGuard = onScopeExit([&]() { i = 666; }); // [1]
// ... (some work)
} // (lambda [1] being ? called on scope exit)
int i = 0;
};
A a;
int main() {
a.f();
std::cout << a.i << std::endl;
}
The compiler in question is:
Apple LLVM version 9.1.0 (clang-902.0.39.2)
Target: x86_64-apple-darwin17.7.0
Aucun commentaire:
Enregistrer un commentaire