first knowledge:

1. dynamic allocation

- Allocating Memory with new - http://devgraphy.tistory.com/7?category=810547

- Freeing Memory with delete - http://devgraphy.tistory.com/8?category=810547

 

 

 

 

Why Am I Reading This?

한 차례, Automatic Storage, Static Storage, and Dynamic Storage(http://devgraphy.tistory.com/15)에서 static의 일반적인 개념에 대해서 다룬 바 있다. 이것은 class와 상관없이 static Keyword를 써줄 경우, 프로그램이 종료될 때까지 존재하는 static storage에 저장되는 개념을 배웠는데, 이러한 개념은 class member에 쓰이는 static에 와서도 크게 변하지 않는다.

 

 

Why Do I Need It?

먼저 static Class Member를 왜 사용하는지 살펴보자. 가끔 class는 class type을 갖는 개개의 object보다는 class 전체 또는생성된 모든 object와 관련된 data member를 필요할 때가 있다. 예를 들어, bank account Class는 현재 prime interest rate를 나타내는 data member를 필요로 한다 해보자. 이 경우에, 우리는 각각 개별의 object보다는 class 전체와 관련된 rate를 원한다. 즉, prime interest rate가 모든 생성되는 object에 똑같이 적용되기를 원한다. 효율성 관점에서 보면, 각각의 object가 rate를 가질 필요는 없다.

더욱 중요한 것은, rate가 바뀌면, 모든 각 object가 새로운 값을 사용하길 원한다. 이 경우에 static class member를 정의해 주게 된다.

 

A static class member has a special property: A program creates only one copy
of a static class variable, regardless of the number of objects created.That is, a static member
is shared among all objects of that class, much as a phone number might be shared
among all members of a family.

 

 

 

 

그러면 이젠 static Class Member를 구체적으로 어떻게 정의하고 사용하는지 살펴보자.

Context of contents.

 

1. Declaring static members.

2. Using static members

3. Defining static Members

4. In-Class Initialization of static Data Members

5. static Members Can Be Used in Ways Ordinary Members Can’t

1. Declaring static members.

 

다른 member들처럼,  static member는 public 또는 private이 될 수 있다. 'static' data member의 type은 const, reference, array, class type 등등이 될 수 있다. 하나의 예로, 우리는 은행에서 account record를 나타내는 하나의 class를 정의할 것이다. 

 

1
2
3
4
5
6
7
8
9
10
11
12
class Account {
private:
string owner;
double amount;
static double interestRate;
static double initRate();
 
public:
void calculate() { amount += amount * interestRate; }
static double rate() { return interestRate; }
static void rate(double);
};
cs

 

 

class의 static member들은 모든 object들의 바깥에 존재한다. object들은 static data member와 관련된 data를 포함하지 않는다. 따라서, Account object는 두 개의 data member- owner, amount 를 가질 것이다. 이 class에는 모든 Account object들과 share할 오직 하나의 interestRate object만 존재한다.

 

비슷하게, static member function은 class의 어떠한 object에도 속박되어 있지 않다; [각주:1]이것은 this pointer를 갖고 있지 않다. [각주:2]결과적으로, static member function은 const로 선언될 수 없다. 더군다나 static member의 body 안에서 this를 지칭할 수 없다. 이런 제한은

 

When you apply the const qualifier to a nonstatic member function, it affects the this pointer. For a const-qualified member function of class C, the this pointer is of type const*, whereas for a member function that is not const-qualified, the this pointer is of type *.

A static member function does not have a this pointer (such a function is not called on a particular instance of a class), so const qualification of a static member function doesn't make any sense.

 

cf. this - http://devgraphy.tistory.com/20?category=810547,    

http://devgraphy.tistory.com/21?category=810547

 

 

2. Using static members

 

우리는 scope operator(::)을 통해서 static member에 직접 접근이 가능하다.

double r;
r = Account::rate(); // access a static member using the scope operator

 

또한 예상 외로, static members는 class의 생성된 object들의 일부가 아니지만, 우리는 object, reference, 또는 pointer of the class Type을 이용해 static member에 접근이 가능하다.

Account ac1;
Account *ac2 = &ac1;
// equivalent ways to call the static member rate function
r = ac1.rate(); // through an Account object or reference
r = ac2->rate(); // through a pointer to an Account object

 

member function들은 scope operator(::)없이 static member에 직접 접근 가능하다.

class Account {

private:
static double interestRate;
// remaining members as before
public:
void calculate() { amount += amount * interestRate; }
};

 

 

cf. const member function

class 안에서 void func()const {} 와 같이 쓰인 함수를 말하며, object의 ordinary(예들 들어, static, mutable) data member의 값을 변경하지 못하는 함수를 의미한다. const member에서 'this' pointer variable은 pointer to const이다. 또한 member function이 const 인지 아닌 지에 따라 overloading 할 수 있다.

  1. Evidence1 [본문으로]
  2. Conclusion1 [본문으로]

C++ 은 memory를 할당하기 위해 사용하는 방법에 따라 3가지 memory 관리 방식이 있다. : automatic storage, static storage, 그리고 dynamic storage(가끔 free store나 heap으로도 불림)

세가지 방식으로 할당된 data object는 lifetime이 서로 다르다. 우리는 빠르게 각각을 살펴 보겠다. (C++ 11은 thread storage라 불리는 4번째 form을 추가했다.)

 

 

  • Automatic Storage 

함수 안에서 정의된 평범한 variable들은 automatic storage를 사용하고 이 들을 automatic variable이라 부른다. 이 용어는 이 variable들을 포함하는 함수가 호출될 때 자동적으로(automatically) 생기고, 함수가 끝나면 만료된다(expire). 실제로 automatic value들은 이것들을 포함한 block에 지역적(local)이다. block 은 {}사이에 동봉된 코드 부분이다. 지금까지, 우리의 모든 block들은 함수 전체였다. 그러나 함수 안에서도 또 다른 block을 가질수 있으며, 그러한 block들 안에 variable을 정의하면, 그것은 오직 프로그램이 해당 block안에서 문장들을 실행하는 동안만 존재하게 된다. Automatic variable들은 기본적으로 STACK 에 저장된다. (STACK의 구조상) 프로그램이 코드 block에 들어갔을 때,variable들은 순서대로 STACK memory 안에 추가되고, 실행이 block을 떠나면 역순으로 memory에서 해제된다(free) 

 

cf. STACK 구조는 LIFO(Last-in, first-out process)라 불린다. 그래서 STACK은 프로그램 처리에 따라 늘었다 줄었다 한다.

 

  • Static Storage

Static storage는 전체 프로그램의 실행 내내 존재하는 storage이다. variable을 static으로 만드는 2가지 방법이 있다. 하나는 외부적으로(externally) 함수의 바깥에 variable을 정의하는 것이다. 다른 하나는 variable을 선언할 때 static Keyword를 사용하는 것이다:

 

static double fee = 56.50;

 

automatic 과 static stroage에 대해 알아둬야할 메인 포인트는 이런 방법들이 엄격히 "variable들의 lifetime을 정의한다"는 것이다. variable이 전체 프로그램 동안에 존재(static variable)하거나 오직 특정 함수가 실행되는 동안에만 존재한다.(automatic variable) 

  • Dynamic Storage

new 와 delete Operator는 automatic 과 static variable보다 더욱 유연한 접근을 제공한다. 이 operator들은 C++이 free store 또는 heap 이라고 일컫는 memory pool을 관리한다. 이 pool은 static 과 automatic variable들을 위해 사용되는 memory와 구분되어 있다. new 와 delete 는 한 함수 안에 memory를 할당하여 다른 함수에서 해제하는 것을 가능하게 해준다. 따라서, data의 lifetime은 프로그램이나 함수의 lifetime에 영향받지 않는다. new 와 delete 을 함께 사용하는 것은 ordinary variable들을 사용하는 것보다 프로그램이 memory를 사용하는 방식에 있어서 더 나은 제어를 제공한다. 그러나 memory 관리는 더욱 복잡해진다. STACK에서는,  자동적인 추가, 제거 메커니즘이 memory부분이 계속 이어져있는 반면에 new와 delete 의 상호작용은 사용되는 memory의 lifetime이 달라지다보니 free store에 구멍을 남길 수 있다. 

 

 

---------------------------------------------------------------------

Management Records

Chapter 9. Memory Models and Namesapces - Storage Duration, Scope, and Linkage

---------------------------------------------------------------------

 

'객체 지향 설계' 카테고리의 다른 글

Knowing Your Objects: this Pointer 1.  (0) 2018.02.25
static Class Members  (0) 2018.02.25
C++ inline functions  (0) 2018.02.21
동적 할당) Freeing Memory with delete  (0) 2018.02.21
동적 할당) Allocating Memory with new  (0) 2018.02.21

+ Recent posts