假设我有这个代码(不要介意SecondsToMinutes和MinutesToHours是彼此的副本)
inline float SecondsToMinutes(float seconds) { return seconds / 60.0; } inline float MinutesToHours(float minutes) { return minutes / 60.0; } inline float HoursToDays(float minutes) { return minutes / 24.0; } inline float SeconndsToHours(float seconds) { return MinutesToHours(SecondsToMinutes(seconds)); } inline float MinutesToDays(float minutes) { return HoursToDays(MinutesToHours(minutes)); } inline float SeconndsDays(float seconds) { return MinutesToDays(SecondsToMinutes(seconds)); }
这是内联的有效用法吗?是否有意义?这是好习惯吗?毕竟,如果我没记错的话,内联意味着函数调用被函数体替换,所以
return MinutesToDays(SecondsToMinutes(seconds))
应该相当于
return seconds / 60.0 / 60.0 / 24.0
对?
或者为此使用宏更好吗?
#define EXCHANGE_SEC_MIN(x) (x / 60.0) #define EXCHANGE_MIN_H(x) (x / 60.0) #define EXCHANGE_H_D(x) (x / 24.0) #define EXCHANGE_SEC_H(x) (EXCHANGE_MIN_H(EXCHANGE_SEC_MIN(x))) #define EXCHANGE_MIN_D(x) (EXCHANGE_H_D(EXCHANGE_MIN_H(x))) #define EXCHANGE_SEC_D(x) (EXCHANGE_MIN_D(EXCHANGE_SEC_MIN(x)))
哪一个更好的做法?或者两者都不是?我希望其他人能分一杯羹.
解决方法
Is this valid usage of inline? Does it make sense?
嗯,是的但没有.
在这一点上它并没有伤害任何东西,但也没有做你认为它做的事情.
在一个excellent post about inline
deft_code中正确地说:
It is said that
inline
hints to the compiler that you think the
function should be inlined. That may have been true in 1998,but a
decade later the compiler needs no such hints. Not to mention humans
are usually wrong when it comes to optimizing code,so most compilers
flat out ignore the ‘hint’.
因此,如果你这样做,它不会伤害任何人,但你的编译器听取你的提示的几率几乎为0.如果它认为适合内联代码,它本身就会这样做.
现在内联主要用于链接器,因为它允许多个编译单元中的多个定义.
如果您想确保您的代码尽可能快,并且您可以访问C 11,那么您应该使用constexpr:
constexpr float SecondsToMinutes(float seconds) { return seconds / 60.0; } //etc..