Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ setting timeval members

Tags:

c++

timeval

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?

like image 574
donalmg Avatar asked Apr 08 '26 09:04

donalmg


1 Answers

  • 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)?

like image 53
Karl Knechtel Avatar answered Apr 09 '26 22:04

Karl Knechtel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!