static function but variable which restore the result

#include "stdafx.h"
#include <iostream>
using namespace std;

class T
{
public:
T() : m_data(0)
{}
~T(){}
private:
T(const T &other){}
T &operator=(const T &other){}

public:
// Interface
int QueryWmi()
{
// Here do something that maybe fail

// But we just assume function success.
m_data = 12345;
return 0;
}

void Show()
{
cout <<m_data <<endl;
}


private:
// data
int m_data;
};

/*
* Query Wmi and restore the result to 't'.
* Param:
* ...
* Rtn:
* ...
*/
int foo(T &t)
{
return t.QueryWmi();
}

/*
* Some logic action using information of Wmi.
*/
int bar()
{
T t;
static int cnt = foo(t); // Only once query Wmi for effeciency.
if (0 != cnt) // If query failed, try again.
{
return -1;
}

t.Show();

return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
bar(); // Right?
bar(); // And this time, Right?

return 0;
}

We know that 'foo()' will execute only once, that's true, but why the second result output '0' as result? 

The reason is local variable 't' in function 'bar'. That local variable 't' will destroy at the end of function call. 

First time function 'foo' executed while 'bar' is called, but the second time while 'bar' is called, the function 'foo' will not execute at all, in which case, local variable 't' in function 'bar' is not initialized. This is why the second result is Zero( or be whatever other ).

 

This error code told me: Never use local variable as out parameter in function which only execute under condition control.

 

This is a real experience in my code while I'm practising in Microsoft China in January 2010. That code appeared in OGC v2.5.1.2, which found by my colleague Xi Yang. Thank you Xi Yang.

转载于:https://www.cnblogs.com/walfud/articles/2325044.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值