简体   繁体   English

为什么不允许将 constexpr 局部变量作为默认 function 参数?

[英]Why is a constexpr local variable not allowed as a default function parameter?

I thought I understood why C++ won't allow a local variable as a default function parameter:我想我明白为什么 C++ 不允许将局部变量作为默认 function 参数:

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 :但即使该变量是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:但是,允许使用全局变量(即使是非 constexpr):

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?有人可以解释在这种情况下不允许 constexpr 局部变量的理由吗? 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.当默认值是固定的并且在编译时已知时,编译器似乎应该能够为 function 构造适当的“默认参数”重载。

It is an issue regarding lifetimes.这是一个关于寿命的问题。 Lets modify your function to让我们将您的 function 修改为

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.现在,在get_functor的调用站点,您会得到一个 lambda ,其默认值是不再存在的 object 的值。 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.由于每次调用 function 时都会评估默认参数,而相应参数没有参数,因此您需要初始化表达式在所有范围内都有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM