English 中文(简体)
Static variables in instance methods
原标题:

Let s say I have this program:

class Foo {
 public:
    unsigned int bar () {
        static unsigned int counter = 0;
        return counter++;
    }
};

int main ()
{
    Foo a;
    Foo b;
}

(Of course this example makes no sense since I d obviously declare "counter" as a private attribute, but it s just to illustrate the problem).

I d like to know how C++ behaves in this kind of situation: will the variable "counter" in the bar() method be the same for every instance?

最佳回答

Yes, counter will be shared across all instances of objects of type Foo in your executable. As long as you re in a singlethreaded environment, it ll work as expected as a shared counter.

In a multithreaded environment, you ll have interesting race conditions to debug :).

问题回答

By "be the same for every instance" you mean there will be one instance of this variable shared across each class instance, then yes, that s correct. All instances of the class will use that same variable instance.

But keep in mind that with class variables you have to take things like multi-threading into account in many cases, which is a whole different topic.

From The C++ Programming Language (2nd edition), page 200, by Bjarne Stroustrup:

Don t use static except inside [plain] functions (§7.1.2) and classes (§10.2.4).

Your example was a couple lines away from being something you could compile and test:

#include <iostream>
using namespace std;
class Foo {
 public:
    unsigned int bar () {
        static unsigned int counter = 0;
        return counter++;
    }
};

int main ()
{
    Foo a;
    Foo b;

    for (int i=0; i < 10; i++)
      cout<<i<<". "<<a.bar()<<" / "<<b.bar()<<endl;
}

The output looks like this:

0. 1 / 0
1. 3 / 2
2. 5 / 4
3. 7 / 6
4. 9 / 8
5. 11 / 10
6. 13 / 12
7. 15 / 14
8. 17 / 16
9. 19 / 18

So yes, the counter is shared across all instances.

You just need to grasp two things:

  1. Static variables are stored in static area of the executing program (which is same as that of global variable).
  2. Scope is limited by the general rules of parentheses.Additionally static variables have internal linkage.




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签