为什么返回类型上的类型限定符没有意义? [英] Why is a type qualifier on a return type meaningless?
问题描述
说我有这个例子:
char const * const
foo( ){
/* which is initialized to const char * const */
return str;
}
什么是正确的方法来避免编译器警告type qualifier返回类型是无意义的?
What is the right way to do it to avoid the compiler warning "type qualifier on return type is meaningless"?
推荐答案
但非类类型的值不可修改(继承自C),因此标准表示非类类型的值不会是const限定的(最右边的const被忽略,即使你指定的),因为const会有点冗余。一个不写它 - 例如:
The way you wrote it, it was saying "the returned pointer value is const". But non-class type rvalues are not modifiable (inherited from C), and thus the Standard says non-class type rvalues are never const-qualified (right-most const was ignored even tho specified by you) since the const would be kinda redundant. One doesn't write it - example:
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
生成的右值表达式,const将被忽略。所以下面是一个错误:
Notice that for the type of "g", the const is significant, but for rvalue expressions generated from type int const
the const is ignored. So the following is an error:
int const f();
int f() { } // different return type but same parameters
我知道你可以观察到const,除了获得类型的g本身(并传递& f
到一个模板,并推断其类型,为例)。最后注意char const和const char表示相同的类型。我建议你用一个概念来解决,并在整个代码中使用。
There is no way known to me you could observe the "const" other than getting at the type of "g" itself (and passing &f
to a template and deduce its type, for example). Finally notice that "char const" and "const char" signify the same type. I recommend you to settle with one notion and using that throughout the code.
这篇关于为什么返回类型上的类型限定符没有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!