【发布时间】:2021-12-04 11:31:32
【问题描述】:
查看此代码:
COleDateTime CSpecialEventDlg::GetSpecialEventDate() noexcept
{
COleDateTime datEvent;
if (datEvent.SetDateTime(m_datEvent.GetYear(),
m_datEvent.GetMonth(),
m_datEvent.GetDay(),
0, 0, 0) != 0)
{
// Error
}
return datEvent;
}
我的代码分析表明我可以添加noexcept(我做了)。但我决定再调查一下。我注意到SetDateTime 返回一个值:
Zero如果此COleDateTime对象的值设置成功;否则,1。此返回值基于DateTimeStatus枚举类型。有关详细信息,请参阅SetStatus成员函数。
对于后一个函数 (SetStatus),它声明:
status 参数值由
DateTimeStatus枚举类型定义,该枚举类型在COleDateTime 类中定义。详情请见COleDateTime::GetStatus。
现在,GetStatus 的文档记录了以下定义:
DateTimeStatus GetStatus() const throw();
因此,如果出现错误,它会引发异常。因此,我决定查看SetDateTime的MFC源码:
inline int COleDateTime::SetDateTime(
_In_ int nYear,
_In_ int nMonth,
_In_ int nDay,
_In_ int nHour,
_In_ int nMin,
_In_ int nSec) throw()
{
SYSTEMTIME st;
::ZeroMemory(&st, sizeof(SYSTEMTIME));
st.wYear = WORD(nYear);
st.wMonth = WORD(nMonth);
st.wDay = WORD(nDay);
st.wHour = WORD(nHour);
st.wMinute = WORD(nMin);
st.wSecond = WORD(nSec);
m_status = ConvertSystemTimeToVariantTime(st) ? valid : invalid;
return m_status;
}
它使用ConvertSystemTimeToVariantTime 来设置状态。 那个用途:
inline BOOL COleDateTime::ConvertSystemTimeToVariantTime(_In_ const SYSTEMTIME& systimeSrc)
{
return AtlConvertSystemTimeToVariantTime(systimeSrc,&m_dt);
}
而那个使用:
inline BOOL AtlConvertSystemTimeToVariantTime(
_In_ const SYSTEMTIME& systimeSrc,
_Out_ double* pVarDtTm)
{
ATLENSURE(pVarDtTm!=NULL);
//Convert using ::SystemTimeToVariantTime and store the result in pVarDtTm then
//convert variant time back to system time and compare to original system time.
BOOL ok = ::SystemTimeToVariantTime(const_cast<SYSTEMTIME*>(&systimeSrc), pVarDtTm);
SYSTEMTIME sysTime;
::ZeroMemory(&sysTime, sizeof(SYSTEMTIME));
ok = ok && ::VariantTimeToSystemTime(*pVarDtTm, &sysTime);
ok = ok && (systimeSrc.wYear == sysTime.wYear &&
systimeSrc.wMonth == sysTime.wMonth &&
systimeSrc.wDay == sysTime.wDay &&
systimeSrc.wHour == sysTime.wHour &&
systimeSrc.wMinute == sysTime.wMinute &&
systimeSrc.wSecond == sysTime.wSecond);
return ok;
}
此时我迷路了。简而言之,我假设SetDateTime 不会抛出异常。
我明白这一点,如果我决定在if 子句中调用GetStatus,那么我们确实有可能引发异常。
【问题讨论】:
-
我没有留下我原来的一堆 cmets,而是决定将它们合并成一个答案。不确定它是否完全解决了您的疑虑,但它可能会在某种程度上消除您的疑虑。
-
嗨 Andrew,我前段时间放弃了使用 COleDateTime。它仍然在我的一些代码中,但我有一个日期类,可以在我替换它时吃掉 COleDateTime。对我来说最重要的是他们使用双倍!??? Leap years?? the paste 如果你愿意。您现在可以访问所有 boost::gregorian 的好东西!
-
@lakeweb 多年来,我在我的项目中大量使用了
COleDateTime,并针对波兰语和马耳他语等语言进行了一些微调。所以我不愿意改变我现在使用的类。但是感谢您的链接。
标签: visual-c++ mfc code-analysis noexcept coledatetime