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

问题描述 投票:0回答:3

出于学习目的,我正在用 C++ 编写一个简单的日志记录类。我的代码包含一个返回今天日期字符串的函数。但是,每当调用“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
放入项目属性中的预处理器定义中。这产生了未解决的外部错误。

有人知道该怎么做吗?

c++ date datetime localtime ctime
3个回答
60
投票

问题在于

std::localtime
不是线程安全的,因为它使用静态缓冲区(在线程之间共享)。
POSIX
Windows
都有安全的替代方案:localtime_rlocaltime_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)};
}

0
投票

使用 C++20 chrono 库更新了答案

    auto now            = std::chrono::system_clock::now();
    auto time_point     = std::chrono::time_point_cast<std::chrono::days>(now);
    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());

-2
投票

尝试在

#define _CRT_SECURE_NO_WARNINGS
任何其他头文件之前
#include
,如以下代码

#define _CRT_SECURE_NO_WARNINGS
#include <ctime>
//your code
© www.soinside.com 2019 - 2024. All rights reserved.