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.

posted @ 2012-01-17 22:01  walfud  阅读(198)  评论(0编辑  收藏  举报