开发者

C++ Determining if a variable is set

I have a variable that is defined:

SYSTEMTIME m_TOTime;

And I call GetSystemTime Function to get the UTC Time:

GetSystemTime( &m_TOTime );

Is it possible to determine if GetSystemTime has been called to set m_TOTime? I have another function that uses this variable, but if GetSystemTime has not been called (which sometimes it doesnt have to be) 开发者_开发技巧it returns a blank object. I was hopeing something like m_TOTime == null would work.


Use an initializer.

SYSTEMTIME m_TOTime = { 0 };  // Initialize structure to zero

...

if (m_TOTime.wYear != 0)
    // structure has been initialized

In general, you cannot do this if all possible values of the variable are "legal", but assuming time travel is impossible, the year will never be zero after GetSystemTime() is called.

If all possible values were legal, you would need to use an auxiliary "bool m_TOTime_initialized = false" variable or somesuch.


You should initialize it with a value which can't be the result of a call to GetSystemTime. Most probably a value of 0 should do the job - usually the system time is counted from an arbitrary moment in the past, like Jan 1, 1970, 00:00:00, which is not going to happen again :-) And the counter may wrap around sometime in the future, but it should happen in the fairly distant future, like 2038*. Until then, you may be safe :-)

*The exact details are os specific.


You can assign the variable some magic value. For example,

SYSTEMTIME m_TOTime = {0}; // This should set all struct to 0

Then you can check if it GetSystemTime was called like so:

if (m_TOTime.wYear != 0) {
    // we have set the value with the GetSystemTime call
}

Of course, you can pick something else other than 0, for example -1 or a value that is guaranteed to not be returned by GetSystemTime.

Alternatively, you can have a boolean flag that will tell you if the variable was set:

SYSTEMTIME m_TOTime;
bool m_TOTime_set = false;
...
GetSystemTime(m_TOTime);
m_TOTime_set = true;
...
if (m_TOTime_set) {
    // do stuff here
}


An alternative approach, wrap it in a class that initializes on construction:

class clock
{
public:
    clock()
    {
        system();
    }

    void system()
    {
        GetSystemTime(&time_);
    }

    void local()
    {
        GetLocalTime(&time_);
    }

    const SYSTEMTIME& get() const
    {
        return time_;
    }

private:
    SYSTEMTIME time_;
};

Its probably overkill, but you will avoid issues with epoch wrapping (assuming GetBlahTime is appropriately changed in the future), further you could go an extra step and wrap access to all the params of SYSTEMTIME and then you can choose a different time implementation for different platforms or whatever, finally you can write operators/methods that do common things for you (time comparisons, delta time, stopwatch, etc.).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜