DarkAtom
DarkAtom

Reputation: 3161

Static variables in member function

I have this class:

#include <cstdio>
#include <cstring>

class Number
{
    int data;
public:
    int get()
    {
        return data;
    }
    char* to_str(int& size)
    {
        static char str[10];
        snprintf(str, 10, "%d", data);
        size = strlen(str) + 1;
        return str;
    }
};

I know that returning static arrays is dangerous (i. e. not thread-safe etc.) and that, since I am using C++ I should use std::string.

What I am interested in here is how this works. Since each method is only compiled once, and it's code is then used by all objects (through the invisible first argument, accessible as the this pointer), this leaves me with a dillema: is that static array unique for each object of that class or is it shared for all objects? Again, I am interested in the mechanic (for learning purposes) and not for good coding practices (the code above is definitely not good code).

Upvotes: 2

Views: 57

Answers (1)

Acorn
Acorn

Reputation: 26066

Since each method is only compiled once

It is compiled several times, given it is an inline definition (assuming your class is in a header and it is included by several translation units (TUs)).

If you were providing the definitions in a TU (a .cpp file), then you are right.

and its code is then used by all objects (through the invisible first argument, accessible as the this pointer)

Note that this pointer is not related to whether static data members and static local variables are shared or not, regardless of whether the code is or not shared across the program.

is that static array unique for each object of that class or is it shared for all objects?

Static local variables in methods (member functions) are unique, i.e. shared between all instances (the same as with any other function).

Upvotes: 2

Related Questions