简体   繁体   English

g ++编译器忽略const返回类型

[英]g++ compiler ignoring const return type

I'm one of these types of people who thinks "if it shouldn't be able to change, then it should be const ". 我是其中一类人,他们认为“如果它不能改变,那么它应该是const ”。 Perhaps I take const to the extreme by doing this, but, since my function return types generally should not be able to change, I declare all my functions to return const . 也许我通过这样做将const带到极端,但是,由于我的函数返回类型通常不应该改变,我声明我的所有函数都返回const (Unless they return void of course - does it even make sense to return by const void ?) (除非它们当然void - 通过const void返回它是否有意义?)

You probably think either I'm kind of nutty, and I'm wearing out my keyboard typing stuff I don't need to, or that returning const makes sense because you already use it yourself. 你可能认为我有点疯狂,而且我的键盘输入我不需要,或者返回const有意义,因为你已经自己使用它了。 Or maybe you're thinking neither of those things in which case I guessed incorrectly. 或者也许你在考虑这些事情,我猜错了。

I've compiled my program using g++4.8, and enabled the compiler switch -Wextra . 我用g ++ 4.8编译了我的程序,并启用了编译器开关-Wextra When doing so, g++ warns me that it ignores every single one of my return statements. 这样做时,g ++警告我它忽略了我的每一个返回语句。 None of them are returning by const . 它们都不是由const返回的。 This makes no difference after compiling obviously, but I wanted to know is there a way of forcing g++ to compile and pay some attention to my const return types. 这显然在编译后没有任何区别,但我想知道是否有一种方法可以强制g ++编译并注意我的const返回类型。

More importantly, why does g++ ignore the const -- or is it simply because I'm nutty and g++ thinks returning const is unnecessary? 更重要的是,为什么g ++会忽略const - 或者仅仅因为我是坚果而g ++认为返回const是不必要的?

As requested: Example... 根据要求:示例......

inline const bool collisionTest(...) { ... }

warning: type qualifiers ignored on function return type

It doesn't ignore it, it's just useless if you return primitive types by value. 它不会忽略它,如果按值返回原始类型,它就没用了。

Returning by value means you can't modify whatever it is you returned anyways, because it's an r-value. 按值返回意味着你不能修改你返回的任何东西,因为它是一个r值。 The const would be redundant. const是多余的。

See: 看到:

int foo();

How would you modify the return? 你会如何修改回报?

foo() = 4;

would yield a compiler error. 会产生编译器错误。

If you return a reference though, the const does matter: 如果你返回一个引用,const确实很重要:

int& foo();
const int& goo();

foo() = 42;  //okay 
goo() = 42;  //error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM