사전지식:

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

Class 코드는 Section 164(http://devgraphy.tistory.com/11?category=810224)와 다른게 없다. 다만, main에서 object를 동적 할당하기 때문에 object 선언하는 부분만 다르다.

int main()
{
    Car* c1 = new Car;    //dynamically create a class object
    cout << *c1;        //print out the object that c1 is pointing
    c1->speedUp();
    cout << *c1;
    c1->speedUp(25);
    cout << *c1;
    Car* c2 = new Car;
    Car* c3 = new Car;
    c1->speedDown(25);
    c2->speedUp(30);
    c3->speedUp(35);
    cout << *c1;
    cout << *c2;
    cout << *c3;
    delete c1;        //memory deallocation
    delete c2;
    delete c3;
}

작성한 class는 object를 생성할 때((line3,9,10)) class 영역에 컴파일되어 올라간다. 이 영역에 올라간 클래스는 설계도(흔한 예로, 붕어빵 틀)로 사용된다. c1은 object가 생성되면서 STACK영역에 올라간다(object의 주소를 STACK에 보관). 생성된 object를 "Instance"라고도 부른다.

c1은 object를 생성할 때 Car(double _v=0) 생성자를 호출한다. 또한 c1은 HEAP에 생성된 object를 reference(참조)한다.

Section 164에서의 object는 STACK 영역에서 빠르게 생성되고 자동으로 STACK에서 소멸된다( block( '}' )을 만남과 동시에!).

STACK에 생성된 c1,c2,c3 Pointer variable들은 HEAP에 생성된 object를 간접적으로 참조한다. 따라서 ->를 이용한다( '.' 과 구분!)

HEAP에는 STACK 영역보다 더 넓고, 필요한 만큼의 memory를 필요할 때 사용하므로 memory leak이 더 적다.

정리하면, object를 HEAP에 생성하는 것을 "object를 동적으로(dynamically) 생성한다"라고 말하며, 사용한 다음에는 반드시 delete를 사용해 제거해야한다. delete를 사용하면, ~Car() destructor를 호출하여 memory에서 object를 제거한다(Memory Deallocation). (Pointer variable c1, c2, c3를 제거하는 게 아니고 따라서 재활용 가능하다)

생성한 object를 delete하지 않으면 HEAP에 memory를 차지하게 된다. 이를 "Memory leak"이라 한다.

[그림: 객체 생성과 용어]

[그림: 객체 생성과 메모리]