c++ - 两个 time_point 实例之间的差异不是持续时间吗?

标签 c++ g++ chrono

我不明白为什么这段代码会被 g++ 4.7.2 卡住:

#include <chrono>

main ()
{
    std::chrono::system_clock::time_point t1, t2 ;
    std::chrono::seconds delay ;

    t1 = std::chrono::system_clock::time_point::max () ;
    t2 = std::chrono::system_clock::now () ;
    delay = t1 - t2 ;
    // t1 = t2 + delay ;
    // t1 = t2 - delay ;
}

出现错误:

test.cc: In function ‘int main()’:
test.cc:10:18: error: no match for ‘operator=’ in ‘delay = std::chrono::operator,<std::chrono::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000l> >, std::chrono::duration<long int, std::ratio<1l, 1000000l> > >((*(const std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000l> > >*)(& t1)), (*(const std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000l> > >*)(& t2)))’

在我看来,“time_point - time_point”给出了一个“持续时间”。

最佳答案

它确实会产生一个持续时间,但有不同种类的持续时间。 std::chrono::duration 在表示类型和单位比率上进行模板化。 std::chrono::seconds例如,单位比率为 1,而 std::chono::nanoseconds单位比率为 std::nano , 或 1/1000000000。时间点具有相同的模板参数。

std::chrono::system_clock::time_point的具体单位比例|是实现定义的,但几乎可以肯定小于 std::chrono::seconds .因此,减去这两个时间点产生的持续时间比 std::chrono::seconds 表示的精度要高得多。 .默认行为是不允许使用具有整数表示的持续时间失去精度的分配。因此,您可以使用具有足够精度的持续时间 (std::chrono::system_clock::duration),也可以将结果转换为您想要的持续时间 (std::chrono::duration_cast<std::chrono::seconds>(...))。

关于c++ - 两个 time_point 实例之间的差异不是持续时间吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16221104/

相关文章:

c++ - 无符号整数多重语法

c++ - std::chrono::years 存储真的至少是 17 位吗?

c++ - 为什么我不能使用 chrono 库?

c++ - 系统之间奇怪的 'Sleep' 行为

c++ - Windows中的微秒计时器

c++ - 将 MinGW 从 4.4.1 更新到 4.7.1 后,SFML 项目将无法运行

c++ - 在 64 位机器上编译 32 位 :/usr/bin/ld: cannot find -l<someLibs>

C++ 和 pulseaudio "not declared in this scope"

c++ - 如何使用 howardhinnant 的 C++ 日期库格式化 UTC 时间字符串

c++ - C/C++ 服务器不发送最后几行文件