【发布时间】:2013-08-17 20:43:10
【问题描述】:
我正在尝试使用以下代码在 C++ 中获取当前本地时间:
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
不幸的是,当我使用消息 _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) 调用本地时间(在 __getgmtimebuf -> _malloc_crt 中的某个位置)时,我收到“调试断言失败”。
我是否遗漏了什么,是否需要一些编译标志(我使用的是带有 c++11 的 vs 2012)?
如果没有,我还有什么选择?
我无法发布整个代码,并且隔离更多上下文并不容易。
似乎错误不是来自时间函数,而是来自其余逻辑(因为它们在单独的项目中工作),我会尝试找出导致它的原因,但仍然,我觉得错误有点晦涩难懂。
我正在做的事情是这样的:
#include <iostream>
#include <chrono>
#include <ctime>
#include <string>
#include <thread>
class A
{
public:
void time()
{
//time_t rawtime;
//struct tm * timeinfo;
//time (&rawtime);
//timeinfo = localtime (&rawtime);
time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << std::ctime(&now);
}
};
class B
{
public:
void run(A *a)
{
this->a = a;
this->t = new std::thread(t_f, *this);
this->t->join();
}
~B()
{
delete t;
delete a;
}
friend void t_f(B &b);
private:
A *a;
std::thread *t;
};
void t_f(B &b)
{
b.a->time();
}
int main()
{
B b;
b.run(new A());
return 0;
}
What I didn't know 是 B 的析构函数在连接之前和线程完成工作之前被调用。
解决方案:
- 时间函数(无论来自 ctime 还是 chrono)按预期工作
- 通过指针或 std::ref 将 B 传递给 t_f()
Keith Thompson 和 Mats Petersson 的两个怀疑都是有根据的且正确的,因此我会将 Keith 的回答标记为正确,因为它是解决这个晦涩错误的第一个好线索,即使我最初没有提供足够的信息。
谢谢
【问题讨论】:
-
C++11 中有全新的时间库 -
<chrono>。但是你用的是VS2012,不知道对这个库的支持程度。 -
您可能需要检查
time调用是否实际成功,方法是检查它的返回值。如果调用失败,rawtime的值未定义,可能是无效的时间戳。 -
@DieterLücking 查看任何参考资料,例如this one.
-
对我来说没问题(VS2012 也是)。你能举一个完整的例子吗?
-
仔细阅读错误消息,您似乎在某处损坏了内存。您可能在代码中的某个地方有一个错误,您在某处写的东西超出(或低于)某些东西的范围。
标签: c++ windows visual-studio c++11