I have a lambda operating on std::array
that is initialized and sometimes re-initialized inside the lambda:
std::array<int, 10> nums; // indeterminate values
auto reinitNums{true};
const auto lambda{
[&] (auto&&... args) {
// always initialized before first use
if (reinitNums) {
// ...
reinitNums = false;
}
// use nums
if (condition) {
regenerateNums = true;
}
}
};
// call the lambda a number of times
The array and reinitNums
aren't used outside of the lambda, so moving them into the init capture may be desirable:
const auto lambda{
[
nums = std::array<int, 10>{}, // filled with zeros
reinitNums = true
] (auto&&... args) mutable {
if (reinitNums) {
// rewrite the zeros
reinitNums = false;
}
// as before
}
};
The problem is that this triggers value-initialization:
nums = std::array<int, 10>{}
So does the version with parenthesis:
nums = std::array<int, 10>()
A version with neither nums = std::array<int, 10>
doesn't compile.
Is it possible to have a default-initialized init capture at all?
No, it's not possible directly. The closest you can get is to create your own wrapper class whose default constructor has an empty body, without any member-initializer list, and value-initialize that.