【发布时间】:2021-01-06 08:28:25
【问题描述】:
请考虑下面的代码,特别是观察get_length 返回const size_t。
#include <stdio.h>
const size_t get_length(void)
{
return 123;
}
void foo(void)
{
size_t length = get_length();
length++;
printf("Length #1 is %zu\n", length);
}
void bar(void)
{
// Still 123 because length was copied from get_length
// (copy ellision notwithstanding, which is not the point here)
size_t length = get_length();
printf("Length #2 is %zu\n", length);
}
int main(void) {
foo();
bar();
}
输出:
Length #1 is 124
Length #2 is 123
我从 clang-tidy 收到以下警告:
Clang-Tidy: Return type 'const size_t' (aka 'const unsigned long')
is 'const'-qualified at the top level,
which may reduce code readability without improving const correctness
这个消息有两部分关于返回类型:
- 常量正确性未得到改善
- 代码可读性降低
我理解第一部分,就像在 foo 和 bar 中一样,由于调用者不需要将它们的局部变量指定为 const,最终 const 的正确性没有得到改善, 也就是说,没有什么可以阻止调用者忽略被调用者返回 const 对象的事实。
但我不确定“代码可读性降低”是什么意思——仅仅是因为它可能会给一些人错误的期望,即永远不会修改返回类型吗?或者还有什么其他东西只有在更复杂的返回类型才开始有意义?
我之所以这么问,是因为我认为这里的可读性不会降低,我只是不确定警告背后的意图是什么。谢谢。
【问题讨论】:
-
这里使用
const的原因是什么?如果没有,则会影响可读性。 -
@jdigital 我如何用C语言向你解释使用“const”的原因是什么? IE。它已经说“const”。使用 C 语言我还能告诉你什么?
-
我问你为什么选择在这里使用
const。你可以省略它。 -
这不是重点。我选择了“const”,因为它是语言的一部分,我试图从 clang-tidy 中理解这个特定的信息。代码仅用作说明。
-
@Terry 你可以在那里使用
const,但 Clang-Tidy 也可以正确地将其标记为无效。请参阅相关的Should useless type qualifiers on return types be used, for clarity?、Benefits of using “const” with scalar type?。
标签: c const-correctness clang-tidy