为什么返回类型的类型限定符毫无意义?

说我有这个例子:

char const * const foo( ){ /* which is initialized to const char * const */ return str; } 

什么是正确的方法来避免编译器警告“返回类型的类型限定符是没有意义的”?

你写它的方式,它是说“返回的指针值是const”。 但是非类型的rvalues不可修改(从Cinheritance),因此标准说非类型的rvalues永远不是const限定的(即使你指定的最右边的const也被忽略),因为const有点多余。 一个人不写它 – 例如:

  int f(); int main() { f() = 0; } // error anyway! // const redundant. returned expression still has type "int", even though the // function-type of g remains "int const()" (potential confusion!) int const g(); 

请注意,对于“g”的类型,const 重要的,但对于从int const类型生成的rvalue表达式, int const将被忽略。 所以以下是一个错误:

  int const f(); int f() { } // different return type but same parameters 

除了获取“g”本身的类型(并将&f传递给模板并推断其类型)之外,我无法知道你可以观察到“const”。 最后请注意“char const”和“const char”表示相同的类型。 我建议你解决一个概念并在整个代码中使用它。

在C中,因为函数返回值和限定值是没有意义的。
它可能在C ++中有所不同,请查看其他答案。

 const int i = (const int)42; /* meaningless, the 42 is never gonna change */ int const foo(void); /* meaningless, the value returned from foo is never gonna change */ 

只有对象才有意义。

 const int *ip = (const int *)&errno; /* ok, `ip` points to an object qualified with `const` */ const char *foo(void); /* ok, `foo()` returns a pointer to a qualified object */ 

以前的答案都没有实际回答“正确的方法”这个问题的一部分。

我相信这个答案是:

 char const * foo( ){ 

这表示你正在返回一个常量字符的指针。