TIL static variables don't work inside class methods

I recently dealt with a bug report demonstrating a pretty subtle and apparently trivial bug which I tracked down (fortunately pretty quickly) to somewhere completely unexpected. It turned out that a static variable inside a class method was causing two separate objects to behave dependently on each other; totally the opposite to what I'd assumed it would do - I'd assumed each instance would get its own static space. (For what it's worth, this was a caching optimisation that I didn't want to clutter the class scope with.)

I wondered if this was normal behaviour for the static keyword. Explicitly static variables is a leftover from C and most languages sensibly omit it because it's kind of redundant with OOP, and evidently, confusing. But C++ doesn't get that choice, so I wondered what it would do.

Apparently it is normal behaviour:

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

class C {
public:
	int AddOne() {
		static int counter = 0;
		return ++counter;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	C c1, c2;
	cout << c1.AddOne() << endl;
	cout << c2.AddOne() << endl;
	return 0;
}

Outputs:

12
1
2

Talk is cheap

Leave a comment:

HTML is not valid. Use:
[url=http://www.google.com]Google[/url] [b]bold[/b] [i]italics[/i] [u]underline[/u] [code]code[/code]