static

김대익·2022년 2월 28일

클래스에서의 static은
build의 link과정에서의 static과는 다르다.(static library)

클래스에서 static이 쓰이는 경우는

  • static member function
  • static member variable
  • static variable in a function

이 있다.
먼저 static member function에 대해 알아보자

#include <iostream>
using namespace std;

class Cat {
public:
	void speak() {
    	cout << "meow" << '\n';
    }
    static void staticSpeak() {
    	cout << "CAT!" << '\n';
    }
private:
	int mAge;
}

int main() {
	Cat kitty;
    kitty.speak();
   
    return 0;
}

을 실행해보면 meow가 출력된다.

#include <iostream>
using namespace std;

class Cat {
public:
    static void staticSpeak() {
    	cout << "CAT!" << '\n';
    }
private:
	int mAge;
}

int main() {
    kitty.staticSpeak();
   
    return 0;
}

를 실행해보면 kitty라는 object를 만들지 않고도 CAT!이 출력되는데
그 이유는 static member function은 object와 연관이 없기 때문이다.

이는 class의 this와 연관이 있다.
this는 object의 주소를 가리키는데,
static member function는 이 this와 binding되어 있지 않기 때문에 object를 생성하지 않아도
call이 될 수 있다.
this와 binding되어 있지 않기 때문에 object의 멤버 변수도 가리킬 수 없기 때문에

class Cat {
public:
    static void staticSpeak() {
    	cout << "CAT!" << '\n';
    	cout << mAge << '\n';
    }
private:
	int mAge;
}

이렇게 static함수에서 멤버 변수인 mAge를 호출하려고하면


에러를 뿜게된다.
또한 cout << this->mAge << '\n';처럼 this키워드로 멤버 변수를 가리킬 수 없다.
멤버 변수와 마찬가지로 멤버 변수도 this라는 object주소를 통해 call하는데
static함수에는 this가 들어가지 않아 static함수 내에서는 멤버 함수를 실행할 수 없다.


다음은 static 변수에 대한 이야기이다.

#include <iostream>
class Cat
{
public:
	void speak()
	{
		static int count = 0;
		count++;
		std::cout << count <<"meow" << std::endl;
	};
	
private:
	int mAge;
};



int main()
{
	Cat kitty;
	Cat nabi;
	kitty.speak();
	nabi.speak();
	
	return 0;
}

위처럼 멤버 변수 count를 static으로 선언하고
kitty, nabi 2개의 객체를 만들어 speak함수를 실행해보면

멤버 변수 값이 공유되는 것을 볼 수 있다.

프로세스의 메모리 모델을 보면

stack에 각각의 객체의 stack frame이 생성되고
static 멤버 변수는 heap아래의 static공간에 생성된다.
두 객체 모두 static변수에 접근하기에 이는 공유된다.

0개의 댓글