为什么不允许将 constexpr 局部变量作为默认函数参数?
Why is a constexpr local variable not allowed as a default function parameter?
我想我理解了为什么 C++ 不允许 local 变量作为默认函数参数:
int main () {
auto local{1024};
auto lambda = [](auto arg1 = local){}; // "illegal use of local variable as default parameter"
}
但即使该变量是 constexpr local:
也是不允许的
int main () {
constexpr auto local{1024};
auto lambda = [](auto arg1 = local){}; // "illegal use of local variable as default parameter"
}
但是,全局 变量(即使是非 constexpr)是允许的:
int global;
int main () {
auto lambda = [](int arg1 = global){}; // OK
}
有人可以解释在这种情况下不允许使用 constexpr 局部变量的理由吗?当默认值是固定的并且在编译时已知时,编译器似乎应该能够为函数构造适当的“默认参数”重载。
这是关于生命周期的问题。让我们将您的函数修改为
auto get_functor() {
constexpr auto local{1024};
return [](auto arg1 = local){}; // "illegal use of local variable as default parameter"
}
现在,在 get_functor
的调用点,你得到一个 lambda,它的默认值是一个不再存在的对象的值。由于每次调用函数时都会计算默认参数,而相应参数没有参数,因此您需要初始化表达式在所有范围内都有效。
我想我理解了为什么 C++ 不允许 local 变量作为默认函数参数:
int main () {
auto local{1024};
auto lambda = [](auto arg1 = local){}; // "illegal use of local variable as default parameter"
}
但即使该变量是 constexpr local:
也是不允许的int main () {
constexpr auto local{1024};
auto lambda = [](auto arg1 = local){}; // "illegal use of local variable as default parameter"
}
但是,全局 变量(即使是非 constexpr)是允许的:
int global;
int main () {
auto lambda = [](int arg1 = global){}; // OK
}
有人可以解释在这种情况下不允许使用 constexpr 局部变量的理由吗?当默认值是固定的并且在编译时已知时,编译器似乎应该能够为函数构造适当的“默认参数”重载。
这是关于生命周期的问题。让我们将您的函数修改为
auto get_functor() {
constexpr auto local{1024};
return [](auto arg1 = local){}; // "illegal use of local variable as default parameter"
}
现在,在 get_functor
的调用点,你得到一个 lambda,它的默认值是一个不再存在的对象的值。由于每次调用函数时都会计算默认参数,而相应参数没有参数,因此您需要初始化表达式在所有范围内都有效。