考虑这段代码(使用 VS2015 编译,使用 boost 1.60:

#include <boost/date_time/posix_time/posix_time_duration.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>

int main( int argc, char* argv[] )
{
    uint64_t val = static_cast<uint64_t>( 5000000000 * 1000000 );
    std::cout << val << std::endl;
    boost::posix_time::time_duration the = boost::posix_time::microseconds( val );
    std::cout << the << std::endl;
    auto res3 = the.total_seconds();
    std::cout << res3 << std::endl;
    return 0;
}

它输出:
5000000000000000
1388888:53:20
705032704

前两行没问题。但是,最后一行应该报告 5000000000(5000000000000000 微秒是 5000000000 秒……这正是 (1388888*3600+53*60+20))。

这个705032704从哪里来的??

最佳答案

这是 boost 中一个愚蠢的 Actor 问题:

sec_type total_seconds() const
{
  return static_cast<sec_type>(ticks() / ticks_per_second());
}
ticks()ticks_per_second() 都返回 int64_t(ticks() / ticks_per_second()) 被评估为 5000000000 。但是,由于 boost::posix_time::time_duration::sec_typeint32_t ...static_cast 将 5000000000 (超出 int32_t 范围...最大值是 4294967295 )转换为 705032704 ( =5000000000-4294967295-1 ))。

关于c++ - boost::posix_time::time_duration::total_seconds 有什么问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37299652/

10-11 19:22