#include <iostream>
#include <functional>
int global = 9;
std::function<void()> functor;
int main()
{
int* ptr = &global;
functor = [ptr]
{
functor = nullptr;
std::cout << *ptr << std::endl;
};
functor();
}
Here is variable ptr
captured by lambda, and during functor()
call functor first deleted through functor = nullptr
and then accesses ptr
. I think that ptr
was corrupted since it was a field of a deleted functor. All the compilers successfully performs that program without crashes and print "9", but I still doubt that this is not undefined behavior. Can someone confirm it?
It is indeed undefined.
Here is how you can confirm it:
#include <iostream>
#include <functional>
struct S
{
~S() {std::cout << "~S()\n";}
};
std::function<void()> functor;
int main()
{
functor = [s = S()]
{
functor = nullptr;
std::cout << "End of lambda\n";
};
functor();
}
The code above prints (on GCC and Clang):
~S() ~S() ~S() End of lambda
The 3 destroyed instances are: one captured by the original lambda, one captured by a copy stored in functor
and one captured by a temporary that std::function::operator=(F &&)
for some reason has to make.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With