boost :: posix_time :: time_duration :: total_seconds有什么问题?

时间:2016-05-18 12:27:37

标签: c++ boost

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

m = [[abs(j-i) for j in range(6)] for i in range(6)]

输出:

#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;
}

两个第一行都可以。但是,最后一行应报​​告5000000000(5000000000000000微秒是5000000000秒....这正是(1388888 * 3600 + 53 * 60 + 20))。

5000000000000000 1388888:53:20 705032704 来自哪里?

1 个答案:

答案 0 :(得分:4)

这是一个愚蠢的演员问题:

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会将5000000000int32_t范围之外...最大值为4294967295)转换为{{1} (705032704))。