我有一段代码:
auto time_point_a = std::chrono::high_resolution_clock::now();
while (true) {
auto time_point_b = std::chrono::high_resolution_clock::now();
auto counter_ms = std::chrono::duration_cast<std::chromo::milliseconds(time_point_b - time_point_a);
// more code
std::cont << counter_ms.count() << std::endl;
}是否保证counter_ms.count()始终返回有效值?有可能是count()抛出的吗?如果counter_ms超过其基本积分类型的大小(我认为它是long long),会发生什么?我的程序将连续运行几天,我需要知道如果/当counter_ms变得太大时会发生什么。
发布于 2016-02-05 15:18:44
是否保证counter_ms.count()始终返回有效值?
counter_ms持有一个毫秒的单符号整数计数。指定.count()成员函数只返回这个带符号的整数值。
伯爵投球有可能吗?
由于以下两个原因,该成员函数没有标记为noexcept:
noexcept在std::lib中被使用得非常少。在counter_ms的情况下,表示必须是带符号的整型,当然不能抛出副本构造。
这不可能扔出去。
如果counter_ms超过其基本积分类型的大小(我认为它是长的),会发生什么?
您可以使用此程序检查基本的整型:
#include <chrono>
#include <iostream>
#include "type_name.h"
int
main()
{
std::cout << type_name<std::chrono::milliseconds::rep>() << '\n';
}其中"type_name.h“被描述为这里。对于我来说,这个程序输出:
long long标准规范规定,这种类型必须是至少45位的带符号整数类型。这使它至少有+/- 557年。您可以找到使用此程序实现milliseconds的实际范围:
#include <chrono>
#include <iostream>
int
main()
{
using days = std::chrono::duration
<int, std::ratio_multiply<std::ratio<24>, std::chrono::hours::period>>;
using years = std::chrono::duration
<int, std::ratio_multiply<std::ratio<146097, 400>, days::period>>;
std::cout << std::chrono::duration_cast<years>
(std::chrono::milliseconds::min()).count() << " years\n";
std::cout << std::chrono::duration_cast<years>
(std::chrono::milliseconds::max()).count() << " years\n";
}对我来说,它的产出:
-292277024 years
292277024 years巧合的是,我实现了我正在使用的<chrono>实现(libc++)。而实际范围比要求的最小范围大得多的原因是,我找不到45位符号积分类型,不得不接受64位符号整数类型。
当超出此范围时,您将得到与签名积分算术溢出完全相同的行为(指定为未定义的行为)。
https://stackoverflow.com/questions/35222170
复制相似问题