c++ - boost::posix_time::time_duration::total_seconds 有什么问题?

标签 c++ boost

考虑这段代码(使用 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 中的一个愚蠢的转换问题:

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/

相关文章:

c++ - 如何防止 boost::optional<T> 被错误地构造为 0?

c++ - boost::optional 改变了一个隐式函数

python - python venv如何管理C++依赖

c++ - ref-qualifier `const &&` 有什么用?

c++ - 平面和 phong 着色问题

c++ - 如何附加 read_some 缓冲区?

c++ - 在桌面应用程序中使用 OpenGL 进行 GUI 设计有什么缺点?

c++ - 避免输出交错

c++ - 使用 Boost 的 C++ 中的多线程之谜

c++ - 如何声明 std::vector of boost histograms ? boost 直方图的类型是什么?