Jes
Jes

Reputation: 2694

How to create a pointer in the lambda capture list?

How can we create a pointer in a lambda capture list? For example, we can create an integer variable and make the lambda stateful:

auto lambda1 = [a = int{ 5 }]() mutable {
    a = 3;
}

However, when we change a to a pointer, the compiler doesn't work:

auto lambda2 = [a = void* { nullptr }]() mutable {
    a = ...;
}

Another workaround is to declare a pointer outside and then copy it, but this seems very redundant

void* a;
auto lambda3 = [a]() mutable {
    a = ...
}

Upvotes: 2

Views: 221

Answers (1)

JeJo
JeJo

Reputation: 32972

You can static_cast the nullptr to void*

auto lambda2 = [a = static_cast<void*>(nullptr)]() mutable {
    // ..
};

That being said, it looks like you want to capture a pointer to some arbitrary types to the lambda. Shouldn't it be done by using templates? Maybe you want to have a look into the generic lambda or template parameter lists in lambda expressions


Thanks to @HolyBlackCat for pointing out for the fact, that the std::nullptr_t will not work for the case

int x; 
std::nullptr_t p = &x;// error: 'initializing': cannot convert from 'int *' to 'nullptr'

Therefore it can not be used for this case.

You can use the std::nullptr_t as follows
#include <cstddef> // std::nullptr_t

auto lambda2 = [a = std::nullptr_t{}]() mutable {
    // ...
};

std::nullptr_t is the type of the null pointer literal, nullptr. It is a distinct type that is not itself a pointer type or a pointer to member type. Its values are null pointer constants (see NULL), and may be implicitly converted to any pointer and pointer to member type.

Upvotes: 3

Related Questions