我不明白为什么这段代码会被 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/