I’m looking at some C++ code that currently passes an int* array that can be null and does some logic. Let’s say it’s of the following form:
void modifyArray(int* arr = nullptr) {
if (arr) {
*arr += 10;
}
}
I know this is prone to memory leaks and I’m trying to replace with with modern C++ concepts. To my understanding, the best practice would be:
- using
std::array
instead ofint*
- passing by reference to avoid copying
- using
std::optional
to prevent use when empty
I’m having trouble implementing that concept. I tried something like the following (exact logic is not important):
void modifyArray(std::optional<std::array<int, 5>>& optArr = std::nullopt) {
if (optArr) {
for (auto& element : optArr.value()) {
element += 10;
}
}
}
But it doesn’t compile, as std::nullopt
is a constant (Non-const lvalue reference to type 'std::optional<std::array<int, 5>>' cannot bind to a value of unrelated type 'const nullopt_t'
).
I haven’t yet found a method to implement all of the above together. Is this viable?
21