Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Destroying lambda within himself [duplicate]

Tags:

c++

c++11

lambda

#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?

like image 424
Denis Avatar asked Mar 05 '18 16:03

Denis


1 Answers

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.

like image 71
HolyBlackCat Avatar answered Oct 27 '22 11:10

HolyBlackCat