我使用C++在Visual Studio 2005和我理解的閱讀什麼是初始化HRESULT的正確方法?
potentially uninitialized local variable 'hr' used
凡小時被定義爲
HRESULT hr;
什麼是初始化HRESULT的正確方法是很多的警告?
我使用C++在Visual Studio 2005和我理解的閱讀什麼是初始化HRESULT的正確方法?
potentially uninitialized local variable 'hr' used
凡小時被定義爲
HRESULT hr;
什麼是初始化HRESULT的正確方法是很多的警告?
我會用:
HRESULT hr = NOERROR;
你也可以使用
HRESULT hr = S_OK;
兩個設置爲0。
選擇錯誤HRESULT
價值和使用,所以HRESULT hr = E_UNEXPECTED
或HRESULT hr = E_FAIL
會是我期望的好選擇。
取決於聊天你想:
E_FAIL
S_OK
hr
如果隨後的代碼無法初始化,值是不相關的?使用E_UNEXPECTED
不要通過初始化變量來抑制警告。警告告訴你代碼是壞的。修復代碼。
一些有用的技巧:
HRESULT
轉換爲C++異常。從HRESULT
到異常翻譯可以通過使用">>
throwing pattern"一樣(雖然這個例子沒有涉及HRESULT
的IT表明,這一模式推廣到處理大多數C風格的方案)非常簡潔,幾乎做可讀取..
std::ostream& operator<<(std::ostream& stream, wchar_t const s[])
{
Size const nBytes = wcstombs(0, s, 0);
(nBytes >= 0)
|| throwX("wcstombs failed to deduce buffer size");
Size const bufSize = nBytes + 1;
std::vector<char> buf(bufSize);
// The count of bytes written does not include terminating nullbyte.
wcstombs(&buf[0], s, bufSize)
>> Accept<IsNonNegative>()
|| throwX("wcstombs failed to convert string");
return (stream << &buf[0]);
}
這個所需的支持定義根本不復雜,例如像
inline bool throwX(std::string const& s)
{
throw Failure(s);
}
template< class Predicate >
struct Accept: Predicate
{};
template< class Type, class Predicate >
inline bool operator>>(Type const& v, Accept<Predicate> const& isOK)
{
return isOK(v);
}
struct IsNonNegative
{
template< class Type >
bool operator()(Type const& v) const { return (v >= 0); }
};
嗯,又一個'>>'超負荷?這真的是世界需要的嗎? ;) – jalf 2010-10-08 12:21:19
第一段爲+1。 – 2010-10-08 13:02:37
@jalf:我不知道任何其他的'''重載(除了在iostream中)。 – 2010-10-09 15:58:17
不要忽略這個警告,你的代碼是壞的。代碼不在您的代碼片段中。 – 2010-10-08 13:03:25