1) 这些在运行时是否比另一个快?哪个以及为什么?
2) 这发生在编译时还是运行时?
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
编辑:使用constexpr 有帮助吗?
constexpr unsigned short operator"" _ushort( unsigned long long arg ){ return arg; }
最佳答案
让我们看看生成的程序集……使用这个工具:https://gcc.godbolt.org
clang生成的程序集是:(修改你的代码编译)
对于这个输入,
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
生成的程序集是
my_var:
.byte 20 # 0x14
my_var2:
.byte 52 # 0x34
my_var3:
.byte 52 # 0x34
因此,没有性能下降……而是灵 active 的提高…… 虽然运算符函数似乎仍然在某些编译器版本中以某些标志创建......这些值在编译时初始化
关于c++ - C++ 11用户定义的文字比普通类型转换慢吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36377459/