c++/9156: static variables in member functions should not retain value across class instances
stashelp@yahoo.com
stashelp@yahoo.com
Fri Jan 3 12:16:00 GMT 2003
>Number: 9156
>Category: c++
>Synopsis: static variables in member functions should not retain value across class instances
>Confidential: no
>Severity: non-critical
>Priority: medium
>Responsible: unassigned
>State: open
>Class: sw-bug
>Submitter-Id: net
>Arrival-Date: Fri Jan 03 04:16:02 PST 2003
>Closed-Date:
>Last-Modified:
>Originator: Will Styles
>Release: 3.2-1mdk
>Organization:
>Environment:
Mandrake Linux 9.0
>Description:
#include <stdio.h>
#include <string.h>
class CLASS
{
public:
int FUNCTION (void)
{
static int val = 0;
return val++;
}
};
int main (void)
{
CLASS *class1 = new CLASS;
printf ("%i\n", class1->FUNCTION ());
delete class1;
CLASS *class2 = new CLASS;
printf ("%i\n", class2->FUNCTION ());
delete class2;
CLASS *class3 = new CLASS;
printf ("%i\n", class3->FUNCTION ());
delete class3;
return 0;
}
the above program imho should print:
0
0
0
but instead prints:
0
1
2
, despite the fact that a different instance of CLASS::FUNCTION is being used each time, so it should return 0 _every_ single time
>How-To-Repeat:
>Fix:
don't implement static variables in member functions like static variables in ordinary functions (or static member functions) as hidden globals, but rather as hidden class members (disclaimer: i don't actually know internals of gcc)
>Release-Note:
>Audit-Trail:
>Unformatted:
More information about the Gcc-bugs
mailing list