static variable defined in a member function 
Author Message
 static variable defined in a member function

In my VC++6 Sp5 I'm defining many static variables to save time (I have
a VERY slow machine) during multiple calls of member functions such as
this:

int Mydata::LtO(CString& s) {
        static char nlc = _T('\n');    
        static char openb  = _T('<');
        static CString nbb = _T("&nbsp;");
.
.
return num;

Quote:
}

Is this thread-safe? I haven't had any crashes, but of course that's no
proof.  I presume I should actually be using static const... , if I can
use *static* at all.

Thanks in advance.
Max



Fri, 18 Nov 2005 07:05:19 GMT  
 static variable defined in a member function

Quote:

>In my VC++6 Sp5 I'm defining many static variables to save time (I have
>a VERY slow machine) during multiple calls of member functions such as
>this:

>int Mydata::LtO(CString& s) {
>    static char nlc = _T('\n');    
>    static char openb  = _T('<');

NB: If you use _T, use TCHAR, not char.

Quote:
>    static CString nbb = _T("&nbsp;");
>.
>.
>return num;
>}

>Is this thread-safe? I haven't had any crashes, but of course that's no
>proof.

The initialization of the CString nbb is dynamic and occurs at runtime, the
first time control passes through its declaration. This is not thread-safe.
However, the following are thread-safe:

// Not much point in making the TCHAR* static...
const TCHAR* const nbb = _T("&nbsp;");
static const TCHAR nbb[] = _T("&nbsp;");

Quote:
>I presume I should actually be using static const... , if I can
>use *static* at all.

Yes, if these are constants, declaring them const is the way to go. You'd
probably be better off defining a namespace to hold these constants. In
VC++, namespace scope variables are initialized before main() is entered, so
as long as you don't start any threads before you enter main(), there aren't
any thread safety issues.

--
Doug Harrison
Microsoft MVP - Visual C++



Fri, 18 Nov 2005 07:44:06 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. static function access member variable and member function

2. class view dosen't shows member variable's and functions defined with macros

3. C2086 error: static local variables in member functions

4. member function and member variable

5. member function and member variable

6. member function and member variable

7. static functions and non static variables

8. static functions with non-static variables!

9. Getting pointer to non-static member function from C callback function

10. Static class member gives LNK2005: symbol already defined

11. strange problem occur while trying to access member function through static function

12. defining a static CString member

 

 
Powered by phpBB® Forum Software