繁体   English   中英

C ++ 11用户定义的文字比普通的类型转换慢吗?

[英]are C++11 user defined literals slower than normal type casting?

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

因此,不会对性能造成任何影响...而是灵活性的提高。...尽管似乎仍在某些标志下的某些编译器版本中创建了运算符函数。...值在编译时进行了初始化

https://godbolt.org/g/YuJyQd

暂无
暂无

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

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