我使用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