1) is any of these faster than the other at runtime? which and why?
2) does this occur at compile time or runtime?
unsigned short operator"" _ushort( unsigned long long arg ){ return arg; }
unsigned short my_var = 0x1234; // using type and literal
auto my_var = unsigned short(0x1234); // using auto and casting literal to type
auto my_var = 0x1234_ushort; // using auto and user defined literal to cast
edit: does using constexpr help it?
constexpr unsigned short operator"" _ushort( unsigned long long arg ){ return arg; }
所有这些都在编译时初始化,因此对它们中的任何一个都没有运行时影响。
Let us see from the generated assemblies... using this tool: https://gcc.godbolt.org
The assembly produced by clang is: (modified your code to compile)
For this input,
inline unsigned char operator "" _kx ( unsigned long long arg ){ return arg; }
unsigned char my_var = 0x14; // using type and literal
auto my_var2 = (unsigned char) 0x1234; // using auto and casting literal to type
auto my_var3 = 0x1234_kx; // using auto and user defined literal to cast
The assembly generated is
my_var:
.byte 20 # 0x14
my_var2:
.byte 52 # 0x34
my_var3:
.byte 52 # 0x34
So, there is no performance hit... rather a gain in flexibility.... Though the operator function seems to still be created in certain compiler versions under certain flags.... The values are initialized at compile-time
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.