我在程序中使用 std::mktime 设置/获取时间。手册页说明:
The values in time are permitted to be outside their normal ranges.
如果它不能将结果表示为 std::time_t,则返回 -1
我在单元测试中尝试了一切方法来使这个函数失败,但没有成功。 These 只是一些尝试:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <stdlib.h>
int main()
{
setenv("TZ", "/usr/share/zoneinfo/America/New_York", 1); // POSIX-specific
std::time_t t = std::time(nullptr);
std::tm tm = *std::localtime(&t);
std::cout << "Today is " << std::put_time(&tm, "%c %Z")
<< " and DST is " << (tm.tm_isdst ? "in effect" : "not in effect") << '\n';
tm.tm_year = 550;
tm.tm_year = 123456789;
tm.tm_mon = 88;
tm.tm_mday = 200;
//tm.tm_mon -= 100; // tm_mon is now outside its normal range
std::mktime(&tm); // tm_dst is not set to -1; today's DST status is used
std::cout << "100 months ago was " << std::put_time(&tm, "%c %Z")
<< " and DST was " << (tm.tm_isdst ? "in effect" : "not in effect") << '\n';
}
那么,如何设置参数才能让这个函数失败呢?
正如评论中所建议的, I tried INT_MAX 仍然没有失败。所以,这个:
tm.tm_year = std::numeric_limits< decltype( tm.tm_year ) >::max();
if ( -1 == std::mktime(&tm) )
std::cout << "std::mktime() failed)" << '\n';
仍然不会让它失败。
$CXX --version
aarch64-pdm3-linux-g++ (GCC) 6.4.0
最佳答案
您的示例对于建议的输入 std::numeric_limits< decltype( tm.tm_year ) >::max()
确实失败。您的示例不会检查 -1 返回值。如果添加
auto err = std::mktime(&tm); // tm_dst is not set to -1, err is.
err
对于此输入设置为 -1。
您可以在https://ideone.com/GUcM3N处看到失败
您还可以在http://coliru.stacked-crooked.com/a/8288579ec8924d7e处看到失败
两个服务的输出相同:
Today is Thu Apr 19 09:07:40 2018 EDT and DST is in effect
100 months ago was Thu ? 200 09:07:40 -2147481749 EDT and DST was in effect
-1
关于c++ - 如何导致 std::mktime 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49921395/