localtime vs localtime_s和适当的input参数

time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); 

这将返回:警告C4996:'localtime':此函数或variables可能不安全。 考虑使用localtime_s来代替。

 time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime_s ( &rawtime ); 

当我将localtime更改为localtime_s时,得到:错误C2660:'localtime_s':函数不带1个参数

下面是我想在第一个代码块中进行的操作:

  • 创build一个空的time_tvariables。
  • 创build一个指向ctime中定义的timeinfo的指针
  • 将rawtime写入rawtime引用
  • 将原始时间转换成对行人有意义的事物

    1. 我对吗?
    2. localtime_s需要什么第二个input参数?
    3. 如果我忽略了整个当地时间的安全问题,最糟糕的情况是什么?

localtime返回一个指向静态分配的struct tm的指针。

用localtime_s,你传入一个指向struct tm的指针, localtime_s将结果数据写入到结果数据中,所以你的代码将从

 struct tm *timeinfo; timeinfo = localtime(&rawtime); 

像这样的东西:

 struct tm timeinfo; localtime_s(&timeinfo, &rawtime); 

这样,它写入到您的缓冲区,而不是有自己的缓冲区。

localtime_s只是localtime functon的一个微软实现,你可以安全地继续使用locatime因为它符合C ++ ISO标准,而且微软把它标记为“不推荐”。 本地时间函数本身在C ++世界中完全不被弃用。

localtime_s 引用说这些参数应该传递给它:

 _tm Pointer to the time structure to be filled in. time Pointer to the stored time. 

作为轨道亮度竞赛指出, localtime时间不是线程安全以及其他几个时间函数。 我想知道更多关于这个问题,我发现了一个相关的博客文章 ,并对此进行了充分的解释。

下面的引用解释了为什么localtime不是线程安全的:

localtime返回一个指向静态缓冲区的指针(std :: tm *)。 另一个线程可以调用该函数,在第一个线程读完struct std :: tm *的内容之前,可以覆盖静态缓冲区。