Pushing struct in vector overwrites time component

时间:2015-09-01 21:37:33

标签: c++ vector time struct

I'm writing a simple CLI calendar, and I store the data for planned activities in a simple struct composed of a few integers, a string and a pointer to a tm struct.

However, when I push these structs into a vector, all the *tm, and only those, get overwritten by the one of the latest I pushed. Everything else stays the same.

So, if I push "A" for 10/02/2016 and "B" for 5/11/2016, I'll see both entries as planned for 5/11/2016, although every other detail stays the same.

Can anyone help me figure out what's wrong?

In case you want to see the code, it's here

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

Here I'm reading from the savefile, decoding the entries through unwrapAppointment (which I checked to be working), and simply pushing them back.

EDIT: Additional pieces of the code:

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

This is the struct that is giving trouble

The log when trying to read the activities:

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

The encoded activities use mktime and localtime to convert tm into time_t and viceversa. Also, I just noticed that I messed up the converting of months and years, could the problem be it?

2 个答案:

答案 0 :(得分:1)

I'm guessing that your tm pointers are set using gmtime or localtime. You do realise that those functions always return the same pointer? And that if you store that pointer its contents will be overwritten by the next call to gmtime or localtime?

答案 1 :(得分:1)

Speculatively writing an answer without the code, as I'm pretty sure that this is the problem: If you are storing the a tm *timestamp as returned by one of several functions that return struct tm* in your object, then a simple look at your data in the debugger will show that ALL of those timestamps will have the same pointer-value - pointing to a single static struct tm inside the function you call. So whenever you call the function again, ALL the values will be changed to the new value.

Change it so that you have tm timestamp; and then do timestamp = *(whatever()); instead of timestamp = whatever(); [technically extra parenthesis not required]