Reputation: 9212
I want to understand what happens, if we allocate dynamic memory inside a static function? Each call to static function returns the same memory, or every time a new memory is created??
For example-
class sample
{
private:
static int *p;
public:
static int* allocate_memory()
{
p = new int();
return p;
}
};
int* sample::p=NULL;
int main()
{
int *p= sample::allocate_memory();
int *q = sample::allocate_memory();
cout << p << " " << q << endl;
if (p== q)
cout << "we are equal";
}
In this program both memory locations inside main() are different. if we move static int *p; inside allocate_memory() function, like static int *p = new int; both memory location will come same.
I want to understand what is the difference. static is always static, weather it is inside class or inside function, then why behavior is different??
Devesh
Upvotes: 1
Views: 2339
Reputation: 752
Every time you call allocate_memory, a new int is created. p is static, but what it points at will change.
To return a pointer to the same object every time:
static int* allocate_memory()
{
if(!p)
{
p = new int();
}
return p;
}
In your main method, p and q will be different regardless of how allocate_memory works, as they are two different pointers. If you de-reference p and q, you will compare what they are pointing to:
if(*p == *q)
{
cout << "Equal";
}
Upvotes: 0
Reputation: 5116
One of the issues here is that the keyword static
means a lot of different things in C++ depending on context. You have stumbled upon two of these.
If a member variable is declared static
, that means the class itself has one copy of this variable which is shared between all instances.
If a local variable in a function is static
, it means the value of that variable persists in-between function calls. It always refers to the same location in memory, even between calls (or in recursive calls). For such a variable, the initializer is only only executed the first time the function is entered.
So, if you've tried this:
static int* allocate_memory()
{
static int p = new int();
return p;
}
the assignment to a new int()
will only be called the first time you call the function. This is because, when written as part of the variable declaration, it is an initializer. If, however, you would do this:
static int* allocate_memory()
{
static int p;
p = new int();
return p;
}
Then, you would see the same behaviour as in your other case.
Upvotes: 3