Carlos
Carlos

Reputation: 31

Memory management of function pointers and lambdas

I'm relatively new in C++, and I've some questions about memory management.

I'm a C# developer and memory management is easier than C++ because of the garbage collector and I don't know when I've to free memory manually.

For example:

void (*ptr)() = [] { /* 1rst lambda expression code*/ };
ptr = [] { /*2nd lambda expression code*/ };

What happen with the first lambda expression?, Is still in memory?, I've to do something before reassigning 'ptr'?.

If someone can explain to me this particular case and how C++ and memory works I would appreciate it!.

Upvotes: 3

Views: 109

Answers (1)

templatetypedef
templatetypedef

Reputation: 372972

The C++ language handles lambda functions without capture lists as though they were real functions with some compiler-generated name that's different from the names of all other functions. As a result, when you write

void (*ptr)() = [] { /* 1rst lambda expression code*/ };

it's kinda sorta like writing the following:

static void _CompilerGeneratedFn137() {
    /* lambda code */
}

void (*ptr)() = &_CompilerGeneratedFn137;

No memory is actually allocated here (except for the space for the ptr variable itself), and the pointer just points somewhere into the code segment of the program. When you then reassign ptr to point to a different lambda, you're not leaking any memory; you're just changing which anonymous function the ptr variable points at.

Hope this helps!

Upvotes: 2

Related Questions