今天发现一个计算时间的BUG,每次执行操作的时候,结果居然不一样。
代码如下:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 
 | std::string GetTime(const std::time_t ¤tTime, int offset, const char *format_string) {char buffer[80];
 const auto *tm = std::localtime(¤tTime);
 std::strftime(buffer, sizeof(buffer), format_string, tm);
 return buffer;
 }
 int main(){
 time_t time_offset = time(nullptr);
 struct tm *now_ = localtime(&t);
 std::cout << GetTime(time_offset -  now.tm_wday * 24 * 60 * 60, 0,"%Y-%m-%d") << std::endl;
 std::cout << GetTime(time_offset -  now.tm_wday * 24 * 60 * 60, 0,"%Y-%m-%d") << std::endl;
 return 0;
 }
 
 | 
两次打印出来的时间居然不是一致的!
原因是:std::localtime返回的指针是内部变量,下次再调用std::localtime之后,将会对它进行更新,导致每次now.tm_wday实际的值已经改变了。
解决的方法也很简单,对std::localtime进行拷贝就好了。
以后再看到直接返回指针的函数,都要留一下心,看看是不是内部的变量的指针!