C++ - "本地时间" 此函数或变量可能不安全
C++ - 'localtime' this function or variable may be unsafe
我正在为学习目的编写一个简单的记录类。我的代码包含一个返回今天日期字符串的函数。但是,每当称为" localtime"时,我都会出现编译器错误。
std::string get_date_string(time_t *time) {
struct tm *now = localtime(time);
std::string date = std::to_string(now->tm_mday) + std::to_string(now->tm_mon) + std::to_string(now->tm_year);
return date;
}
我尝试使用#define _CRT_SECURE_NO_WARNINGS
。它行不通,出现同样的错误。我还尝试将_CRT_SECURE_NO_WARNINGS
放入项目属性中的预处理器定义中。这给出了未解决的外部错误。
有人对该怎么办有任何想法吗?
问题是std::localtime
不是线程安全,因为它使用静态缓冲区(在线程之间共享)。POSIX
和Windows
都有安全的替代方案:localtime_r和localtime_s。
这是我要做的:
inline std::tm localtime_xp(std::time_t timer)
{
std::tm bt {};
#if defined(__unix__)
localtime_r(&timer, &bt);
#elif defined(_MSC_VER)
localtime_s(&bt, &timer);
#else
static std::mutex mtx;
std::lock_guard<std::mutex> lock(mtx);
bt = *std::localtime(&timer);
#endif
return bt;
}
// default = "YYYY-MM-DD HH:MM:SS"
inline std::string time_stamp(const std::string& fmt = "%F %T")
{
auto bt = localtime_xp(std::time(0));
char buf[64];
return {buf, std::strftime(buf, sizeof(buf), fmt.c_str(), &bt)};
}
C 20 Chrono Library
更新答案 const auto now = std::chrono::system_clock::now();
const auto time_zone = std::chrono::current_zone();
const auto local_time = time_zone->to_local(now);
const auto time_point = std::chrono::time_point_cast<std::chrono::days>(local_time);
const auto year_month_day = std::chrono::year_month_day{ time_point };
int year = static_cast<int>(year_month_day.year());
int month = static_cast<unsigned>(year_month_day.month());
int day = static_cast<unsigned>(year_month_day.day());
在#include
之前尝试使用#define _CRT_SECURE_NO_WARNINGS
,例如以下代码
#define _CRT_SECURE_NO_WARNINGS
#include <ctime>
//your code
相关文章:
- vs 2015 constexpr变量不恒定,但与2019相比还好吗
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 在头文件中定义变量不会出错
- 为什么我的数组值与此处的全局变量不匹配?
- 静态成员变量不会由 gettext 转换
- C++/CLI 和 C#/VB 与不安全和外部有什么区别?
- 是否允许类类型的 std::function 成员变量(不完整类型)?
- 变量不在 lambda 的范围内
- constexpr 函数在编译时获取值,即使我的变量不是 constexpr
- 问:Apache Arrow 数组生成器不安全追加
- 不安全的 MPI 非阻塞通信示例?
- 为什么当我使用 std::string::operator[] 时自动变量不会成为引用?
- Constexpr变量不是编译时值
- 表达式必须具有常数值,变量不能用作定义数组大小的常数
- 有没有一种简单的方法来检查C++中的不安全表达式
- 为什么我的 std::atomic<int> 变量不是线程安全的?
- 变量不能明确
- 如何修复编译错误"此函数或变量可能不安全"(strcpy)
- C++ - "本地时间" 此函数或变量可能不安全
- 本地静态指针变量不是线程安全的