std::chrono的time_point是否会静默溢出?代码异常原因探究
关于std::chrono::time_point::min()与浮点数溢出的问题
以下是相关测试代码:
#include <iostream> #include <chrono> int main() { constexpr std::chrono::duration<float> kLastWarningMsgDuration{ 10 }; // default time point (zero) std::chrono::steady_clock::time_point lastWarningMsgTime1; // minimum time point (some negative value) std::chrono::steady_clock::time_point lastWarningMsgTime2 = std::chrono::steady_clock::time_point::min(); // current time point std::chrono::steady_clock::time_point lastWarningMsgTime3 = std::chrono::steady_clock::now(); bool result1 = std::chrono::steady_clock::now() - lastWarningMsgTime1 >= kLastWarningMsgDuration; bool result2 = std::chrono::steady_clock::now() - lastWarningMsgTime2 >= kLastWarningMsgDuration; bool result3 = std::chrono::steady_clock::now() - lastWarningMsgTime3 >= kLastWarningMsgDuration; std::cout << result1 << std::endl; // true, more than 10 seconds std::cout << result2 << std::endl; // false ??? std::cout << result3 << std::endl; // false, less than 10 seconds }
我还没深入研究,但猜测问题出在第二个结果超出了32位float的存储范围导致溢出。不过某份PPT里的断言让我困惑:
如果你做的合理修改不涉及显式类型转换语法(且能编译通过),你可以确信自己没有引入bug。
现在这个断言动摇了我的认知,我想问问:是我误解了time_point::min()的作用,还是这个断言并不完全正确?
内容的提问来源于stack exchange,提问作者Miro Kropacek
相关产品推荐
相关产品推荐

