简体   繁体   English

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

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

1) is any of these faster than the other at runtime? 1)这些在运行时是否比其他任何一种都要快? which and why? 哪个以及为什么?
2) does this occur at compile time or runtime? 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

edit: does using constexpr help it? 编辑:使用constexpr有帮助吗?

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 让我们从生成的程序集中查看...使用此工具: https : //gcc.godbolt.org

The assembly produced by clang is: (modified your code to compile) clang生成的程序集是:(修改了代码以进行编译)

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

https://godbolt.org/g/YuJyQd https://godbolt.org/g/YuJyQd

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

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