c++ setting timeval members

donalmg picture donalmg · Nov 29, 2010 · Viewed 9.5k times · Source

I have a function which takes two current class level member variables and sets them into a timeval structure, and returns the timeval obj (by value).

I am seeing an issue when setting a class level member timeval object vs creating a new timeval object at each get() call.

Inside the class

protected:
int time[2];
timeval tv;

// work done on setting the time array

timeval getTimeval()
{
    tv.tv_sec = (time_t)time[0];
    tv.tv_usec = time[1];
    return tv;
}

This will not return the correct timeval values. The tv.tv_sec will get overwritten but the tv_usec remains constant. However, it will return the correct values when I create the timeval object inside the get call.

timeval getTimeval()
{
    timeval t;
    t.tv_sec = (time_t)time[0];
    t.tv_usec = time[1];
    return t;
}

Is there any reason setting the timeval objects on a member variable should differ from creating a new object and setting its values?

Answer

Karl Knechtel picture Karl Knechtel · Nov 29, 2010
  • Any chance you've corrupted something somewhere else (undefined behaviour)?
  • Are you using threads? If so, the first approach could have two threads both working on the class member 'tv' at the same time, whereas the second approach has each thread working on its own local timeval instance.

That said, there's really no reason to have the timeval as a class member here; you aren't optimizing anything as is (to avoid constructing a separate instance, you would have to return the class member by reference, rather than by value) so you're just wasting space inside each instance of the class. (Returning the timeval by value isn't especially costly anyway; it's a small, POD struct, being stack-allocated.)

But why are the values starting out in the int array in the first place? Why not just have a timeval data member and work with it directly (and return it by const reference in the accessor)?