说我有这个例子:
char const * const
foo( ){
/* which is initialized to const char * const */
return str;
}
Run Code Online (Sandbox Code Playgroud)
正确的方法是什么来避免编译器警告"返回类型的类型限定符是没有意义的"?
Joh*_*itb 23
你写它的方式,它是说"返回的指针值是const".但是非类型的rvalues不可修改(从C继承),因此标准说非类型的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();
Run Code Online (Sandbox Code Playgroud)
请注意,对于"g"的类型,const 是重要的,但对于从类型生成的rvalue表达式int const,const将被忽略.所以以下是一个错误:
int const f();
int f() { } // different return type but same parameters
Run Code Online (Sandbox Code Playgroud)
除了获取"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 */
Run Code Online (Sandbox Code Playgroud)
只有对象才能被有意义地限定。
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 */
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22054 次 |
| 最近记录: |