「C++17」 static inline 멤버 변수

Fuji ㅣ 2023. 5. 19. 07:56

 

 




C++17부터 static 멤버 변수를 inline으로 선언할 수 있게 되었습니다. 


class Game
{
    // 코드 생략
private:
    static inline size_t sCounter = 0;    
};



다음처럼 static 멤버 변수에 inline 키워드를 같이 선언해주면 소스 파일에 다음과 같이 적지 않아도 됩니다.

 

size_t Game::sCounter; // 더이상 사용하지 않아도 됨

 

static const 데이터 멤버를 활용한 간단한 코드 예시입니다. 사용자가 크기를 정하지 않으면 임의의 크기를 가지도록 다음처럼 활용할 수 있습니다. 클래스에서 상수를 사용할 땐 #define보다는 class constant를 이용하는 것이 유용합니다.

 

Game
{
public:
    // 코드 생략
    size_t getID() const;
    
private:
    static const size_t kMaxHeight = 100;
    static const size_t kMaxWidth = 100;
    
    static size_t sCounter;
    size_t mID = 0;
};

Game::Game( size_t width, size_t height )
    : mID( sCounter++ )
    , mWidth( std::min( width, kMaxWidth ) )
    , mHeight( std::min( height, kMaxHeight ) )

{
    // 코드 생략
}