C++ - "本地时间" 此函数或变量可能不安全

C++ - 'localtime' this function or variable may be unsafe

本文关键字:变量 不安全 函数 时间 C++      更新时间:2023-10-16

我正在为学习目的编写一个简单的记录类。我的代码包含一个返回今天日期字符串的函数。但是,每当称为" 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不是线程安全,因为它使用静态缓冲区(在线程之间共享)。POSIXWindows都有安全的替代方案: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