Domanda

In a MFC application I like to map SQL date values (CDBVariant) to MFC CTime. Because the database entries can be NULL (value does not exist), I wonder if CTime is nullable. The remark in the MFC documentation to CTime::Format makes me thinking, it should be possible:

If the status of this CTime object is null, the return value is an empty string.

  • But how to set this status, is it even possible?
  • If it isn't possible, I guess boost::optional<CTime> would be a good alternative?
È stato utile?

Soluzione

CTime is just a wrapper for a __time64_t. When you call format it does this:

inline CString CTime::Format(_In_z_ LPCTSTR pFormat) const
{
    if(pFormat == NULL)
    {
        return pFormat;
    }

    TCHAR szBuffer[maxTimeBufferSize];
    struct tm ptmTemp;

    if (_localtime64_s(&ptmTemp, &m_time) != 0)
    {
        AtlThrow(E_INVALIDARG);
    }

    if (!_tcsftime(szBuffer, maxTimeBufferSize, pFormat, &ptmTemp))
    {
        szBuffer[0] = '\0';
    }
    return szBuffer;
}

So the system function you want to look at is _tcsftime. And this is where I think the documentation is not very accurate. If the _localtime64_s fails you'll get an exception so a 'null' time can't really be passed to _tcsftime. You'll only get a NULL if _tcsftime fails but that won't be because of a 'null' time.

So, in short, use something like you suggest of boost::optional to represent null.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top