C ++ specifying timeval elements

I have a function that takes two member variables of the current class and sets them to a timeval structure and returns the value of timeval obj (by value).

I see a problem when setting the timeval element of a class level object against creating a new timeval object every time get () is called.

Inside 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 time values. Tv.tv_sec will be overwritten, but tv_usec will remain 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 why setting timeval objects in a member variable should be different than creating a new object and setting its values?

+3
source share
2 answers
  • , - - ( undefined)?
  • ? , , "tv" , , timeval.

, timeval; , ( , , ), . ( timeval , POD, .)

, int, ? timeval ( const )?

+6
//header file header_1.h
#include <time.h>

class header_1{

protected:
    int time[2];
    timeval tv;
public:
    timeval getTimeval();
    void setTimeval();

};


// header_1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <vector>
#include "header_1.h"

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    timeval tv_temp;
    header_1 t1;
    t1.setTimeval();
    tv_temp = t1.getTimeval();


    return 0;
}

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

void header_1::setTimeval()
{
    time[0] = 100;
    time[1] = 111;
}

, , . , , ( ), .

0

Source: https://habr.com/ru/post/1777436/


All Articles