c – 常数,但仅适用于此范围的其余部分
发布时间:2020-12-16 03:24:12 所属栏目:百科 来源:网络整理
导读:我有时会遇到这样的情况,即变量是const是有意义的,但仅适用于其范围的后半部分.例如,块的第一部分可能设置值,如果很明显我们已经“完成”设置该变量,则其余部分的可读性可能会提高 – void foo() { int n; // Do things that result in initialization of n
我有时会遇到这样的情况,即变量是const是有意义的,但仅适用于其范围的后半部分.例如,块的第一部分可能设置值,如果很明显我们已经“完成”设置该变量,则其余部分的可读性可能会提高 –
void foo() { int n; // Do things that result in initialization of n freeze n; // Imaginary construct that declares "n" const for rest of scope // Later steps that depend on 'n' but do not change it } 是否存在捕获此模式的C语言?当然,块的后半部分可以移动到一个单独的功能,但是可以在不移动任何东西的情况下完成吗? 解决方法
而不是将不可变部分包装为lambda,如何将初始化部分包装成lambda并将其作为const int获取?然后就没有机会改变可变的int n.
void foo() { const int n = []() { ; // Do things that result in initialization of n return initialized_n; }(); // Later steps that depend on 'n' but do not change it } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |