簡體   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