vector中的push结构覆盖时间分量

Pushing struct in vector overwrites time component

本文关键字:时间 分量 覆盖 结构 中的 push vector      更新时间:2023-10-16

我正在编写一个简单的CLI日历,我将计划活动的数据存储在一个简单的结构体中,该结构体由几个整数,一个字符串和指向tm结构体的指针组成。

然而,当我把这些结构体压入一个向量时,所有的*tm,只有那些,被我最近压入的那个覆盖。

所以,如果我按下2016年10月2日的"A"和2016年5月11日的"B",我将看到两个条目都计划在2016年5月11日,尽管所有其他细节保持不变。

有谁能帮我弄清楚是怎么回事吗?

如果你想看代码,在这里

while (getline(caleList, tempstring)) {
    cout << tempstring << endl;
    Appointment tempapp = unwrapAppointment(tempstring);
    apps.push_back(tempapp);
}

在这里,我从保存文件中读取,通过unwrapAppointment解码条目(我检查正在工作),并简单地将它们推回去。

编辑:额外的代码:

struct Appointment
{
    int ID;
    bool alarm;
    tm* dateAndTime;
    string text;
};

就是这个结构体出了问题

尝试读取活动时的日志:

Calendar Module Activated. 1 to mark an activity, 2 to read all activities, anything else to return to main.
> 2
Encoded activities:
0|61397616601|First|1
0 First Fri Aug 13 14:30:01 3915 1
1|61424667901|Second|0
1 Second Wed Jun 21 16:45:01 3916 0
2|61416011701|Third|1
2 Third Mon Mar 13 12:15:01 3916 1
Decoded activities:
Activity number 0: First, set for the day 13/2/2016 at 12:15
Activity number 1: Second, set for the day 13/2/2016 at 12:15
Activity number 2: Third, set for the day 13/2/2016 at 12:15

编码的活动使用mktime和localtime将tm转换为time_t,反之亦然。另外,我刚刚注意到我把月份和年份的转换弄乱了,可能是问题所在吗?

推测性地编写没有代码的答案,因为我很确定这是问题所在:如果您正在存储由在对象中返回struct tm*的几个函数之一返回的tm *timestamp,那么简单地查看调试器中的数据将显示所有这些时间戳将具有相同的指针值-指向您调用的函数中的单个static struct tm。因此,无论何时再次调用该函数,所有的值都将被更改为新值。

将其更改为tm timestamp;,然后更改为timestamp = *(whatever());而不是timestamp = whatever();[技术上不需要额外的括号]

我猜你的tm指针是使用gmtimelocaltime设置的。你意识到这些函数总是返回相同的指针吗?如果您存储该指针,其内容将被下一次调用gmtime或localtime覆盖?