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

标签 c++ user-defined-literals

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 的提高…… 虽然运算符函数似乎仍然在某些编译器版本中以某些标志创建......这些值在编译时初始化

https://godbolt.org/g/YuJyQd

关于c++ - C++ 11用户定义的文字比普通类型转换慢吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36377459/

相关文章:

c++ - Ofstream 对象不能使用 << 运算符 C++

c++ - std::function 的重载运算符?

c++ - 双参数构造函数的用户定义文字

c++ - 使用用户定义的文字实现 km/h 和 m/s

c++ - 这个字符串加法是一个有效的表达式吗?

c++ - 如何修改boost::apply_visitor返回值?

c++ - 无法访问私有(private)成员 - 原子

c++ - 等待 DownloadFileAsync 与 ManualResetEvent c++/cli

c++ - `using namespace std::literals` 安全吗?

c++ - 用户定义的文字参数不是 constexpr?