【问题标题】:Understanding "'const' at top level, which may reduce code readability without improving const correctness"在顶层理解“'const',这可能会降低代码的可读性而不提高 const 的正确性”
【发布时间】: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


【解决方案1】:

您可以在那里使用const,但Clang-Tidy 将其标记为无效也是正确的。

Should useless type qualifiers on return types be used, for clarity?Benefits of using “const” with scalar type? 下的相关问答涵盖了为什么const 在这种情况下无效的部分原因。

关于为什么“代码可读性降低”的问题的另一部分,这是因为多余的 const 限定符可能会分散对核心事实的注意力,即 const'ness 不会延续到值分配中.例如,它可能会诱使客户端代码错误地认为返回值必须也可以使用const,例如const size_t val = get_length(); 这不是真的,正如发布的代码所示。

类似的警告也适用于论点。假设const size_t get_length(); 的返回值总是传递给另一个函数baz(get_length());baz 的参数不需要(并且可以说不应该)声明为const size_t,而只是简单的size_t,即void baz(size_t);

【讨论】:

  • 感谢您的解释,现在一切都清楚了!
【解决方案2】:

1。 const 正确性没有提高

返回值只能用作右值。无法更改右值,因此已经给出了 const 正确性。

2。代码可读性降低

你正在引导读者进入错误的假设。

示例

/* the rest of your example... */

void baz(void)
{
    size_t length = get_length();
    length += 42;
    
    printf("Length #2 is %zu\n", length);
}

没有什么可以阻止length的变化。它被一个常量初始化,对,比如size_t length = 123;

/* the rest of your example... */

void fu(void)
{
    const size_t length = get_length();
    length += 42; /* will give a compile-time error */
    
    printf("Length #2 is %zu\n", length);
}

【讨论】:

  • 感谢您的回答-最后我选择了另一个,因为它对我来说更容易理解,但您的也很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多