Reputation: 519
I thought I understood why C++ won't allow a local variable as a default function parameter:
int main () {
auto local{1024};
auto lambda = [](auto arg1 = local){}; // "illegal use of local variable as default parameter"
}
but it's not allowed even when that variable is a constexpr local:
int main () {
constexpr auto local{1024};
auto lambda = [](auto arg1 = local){}; // "illegal use of local variable as default parameter"
}
however, a global variable (even if non-constexpr) is allowed:
int global;
int main () {
auto lambda = [](int arg1 = global){}; // OK
}
Can someone explain the rationale for not allowing a constexpr local variable in this situation? It would seem the compiler should be able to construct the appropriate "defaulted argument" overloads for a function when that default value is fixed and known at compile-time.
Upvotes: 4
Views: 707
Reputation: 180660
It is an issue regarding lifetimes. Lets modify your function to
auto get_functor() {
constexpr auto local{1024};
return [](auto arg1 = local){}; // "illegal use of local variable as default parameter"
}
Now, at the call site of get_functor
, you get a lambda whose default value is the value of an object that no longer exists. Since the default argument is evaluated each time the function is called with no argument for the corresponding parameter, you need the initialization expression to be valid in all scopes.
Upvotes: 5