본문 바로가기
C++

[C++] static에 대하여

by 유노brain 2023. 10. 30.
반응형

Static 변수

static 변수는 프로그램 수명 동안 할당됩니다.

call by value에서 보면 값을 호출하고 나서 값이 초기화되는데

static을 사용할 경우 값이 유지가 됩니다.

 

아래에 static을 사용했을 때와 안했을 때를 비교헤보겠습니다.

static 변수를 선언했을 때
#include <iostream>
#include <string>
#include <string.h>

void foo(){
    static int count = 0;
    std::cout << count++ <<std::endl;
}

int main(){
    for(int i=0; i < 10; i++){
        foo();
    }
    return 1;
}

static 선언시 값

static 변수를 선언할 경우 위의 코드의 값은 사진과 같이 0~9까지 출력이 됩니다.

 

그렇다면 static 변수를 제거하면 어떻게 될까요?

static 변수 선언을 하지 않을때
#include <iostream>
#include <string>
#include <string.h>

void foo(){
     int count = 0;
    std::cout << count++ <<std::endl;
}

int main(){
    for(int i=0; i < 10; i++){
        foo();
    }
    return 1;
}

다음과 같은 출력 결과가 나옵니다.

확인해 보면 모두가 0으로 나오는 것을 확인할 수 있는데요.

이것은 call by value에 있어서 초기화되기 때문입니다.

 

 

이제 객체에서도 어떻게 쓰이는지에 대해 알아보겠습니다.

 

객체에서의 static 

프로그램을 시작할 때 객체가 할당이 됩니다.

객체는 생성자를 처음 실행할 때 즉시 초기화 됩니다.

 

static 객체 선언할 때
#include <iostream>
#include <string>
#include <string.h>

class Node{
    public:
    Node(int value) : value_(value){
        std::cout << "Object creation" <<std::endl;
    } //constructor
    ~Node(){
        std::cout << "Object Deletion"<<std::endl;
    }//Destructor

    private:
    int value_;

};

void foo(){
    static Node n(3);
}

int main(){
    std::cout << "Start main" <<std::endl;
    foo();
    foo();
    std::cout << "End main" <<std::endl;
    return 1;
}

위의 결과를 보면 소멸자(Destructor)는 출력하지 않는 것을 볼 수 있습니다.

즉 static 덕분에 객체가 계속 남아있다는 것을 뜻합니다.

마지막으로 프로그램이 종료한 뒤 객체 할당이 해제됩니다.

그렇기 때문에 소멸자가 나온 것을 확인할 수 있습니다.

 

이제 Node 앞에 static이 없을 때를 확인해 보겠습니다.

static 없이 객체를 선언할 때
#include <iostream>
#include <string>
#include <string.h>

class Node{
    public:
    Node(int value) : value_(value){
        std::cout << "Object creation" <<std::endl;
    } //constructor
    ~Node(){
        std::cout << "Object Deletion"<<std::endl;
    }//Destructor

    private:
    int value_;

};

void foo(){
     Node n(3);
}

int main(){
    std::cout << "Start main" <<std::endl;
    foo();
    foo();
    std::cout << "End main" <<std::endl;
    return 1;
}

Node 앞에 static을 제거하면 위와 같은 결과가 나옵니다.

즉 Node 클래스에서 객체를 생성하고 출력 후 사라지는 것을 확인할 수 있습니다.

그렇기 때문에 소멸자가 온 것이지요.

 

 

static을 멤버 필드에 적용해 보겠습니다.

 

static 멤버 필드

멤버 필드는 클래스의 모든 객체와 공유됩니다.

 

아래 예시코드를 보겠습니다.

#include <iostream>
#include <string>
#include <string.h>

class Node{
    public:
    Node(int value) : value_(value){} //constructor
   
    const static int kNodeVersion = 7;

    private:
    int value_;

};

void foo(){
     Node n(3);
}

int main(){
   Node n1(1);
   Node n2(2);

   std::cout<<Node::kNodeVersion <<std::endl;
   std::cout<<n1.kNodeVersion <<std::endl;
    return 1;
}

값이 두 개다 7이 나오는 것을 확인할 수 있습니다.

즉 static 덕분에 kNodeVersion 변수가 초기화되지 않았다는 것을 확인할 수 있습니다.

 

반응형

댓글