2

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 = ...
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
Jes
  • 2,614
  • 4
  • 25
  • 45
  • 3
    `a=void*{nullptr}` -> `a=(void*)nullptr` although I really question if you need this or not. What are you doing with the pointer? – NathanOliver Aug 09 '21 at 18:22

1 Answers1

3

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.

JeJo
  • 30,635
  • 6
  • 49
  • 88
  • 1
    Using `std::nullptr_t` makes this useless, since such pointer can't be changed to actually point to something. Your first two examples are equivalent to `a = nullptr`. Only the third snippet `a = static_cast(nullptr)` could be useful. – HolyBlackCat Aug 09 '21 at 18:52
  • 1
    `int x; std::nullptr_t p = &x;` doesn't compile. `int x; void *p = &x;` does. – HolyBlackCat Aug 09 '21 at 18:56