Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static variable inside static method doesn't change

I want to create a class which has a static method that returns a reference to a static variable(which is declared inside the method). What I want is when calling the method to get the reference of the static variable. Then when I modify it outside the class and call the method again to get the same value I previously set.

Here's what I tried:

#include <iostream>
using namespace std;

class A
{
public:
    static int& f()
    {
        static int i;
        return i;
    }
};

int main()
{
    static int i;
    i = A::f();

    cout << i << endl;

    i = 11;
    cout << i << endl;

    i = A::f();
    cout << i << endl;

    return 0;
}

The problem is that the output of this code is:

0
11
0
Press <RETURN> to close this window...

Why doesn't it return 0, 11, 11 and how can I make it return 0, 11, 11?

Note: I want the static variable to be explicitly declared inside the method and not as member.

Thanks!

like image 993
Jacob Krieg Avatar asked May 17 '26 01:05

Jacob Krieg


2 Answers

This is because you copy the value returned by reference into a regular variable: when you store int& in an int, it is no longer a reference.

What you should do instead is

int &i = A::f();

Note that the local i needs not be static: reference to static data can be stored in automatic variables without a problem.

like image 134
Sergey Kalinichenko Avatar answered May 19 '26 04:05

Sergey Kalinichenko


To have the local variable i refer to the same variable inside the function, declare it as a reference:

static int& i = A::f();

Otherwise, you're just creating a new variable and using assigning A::f() to it.

like image 25
Luchian Grigore Avatar answered May 19 '26 02:05

Luchian Grigore