Programming Language/C++

[C++] 동적할당

lumana 2024. 2. 4. 08:26

동적할당(Dynamic allocation)


동적할당(Dynamic allocation)이란

  • 동적으로 할당되지 않은 변수의 경우

    • 지역변수 : 지역변수가 속한 함수가 시작할 때 생성되고, 종료되면 소멸됨

    • 전역변수 : 프로그램 시작과 동시에 생성되고, 종료되면 소멸됨

  • 동적 할당 dynamic allocation : 프로그램 실행 중에 변수를 메모리에 할당하는 것

변수 동적할당

int main(void) {
    // int a = int(5);
    int *a = new int(5);  // new 는 연산자.
                          /*
                          작동원리:
                          int(5)에서 메모리 상에 인트형을 저장하는 공간이 생겨나 5가 들어감(200번지). new가 이 공간의 주솟값(200번지)을 a에 넘겨줌.
                          */
    cout << a << endl;
    cout << *a << endl;
    *a = 10;
    cout << a << endl;
    cout << *a << endl;

    delete a; // 메모리 해제
}
  • (new) (자료형의 생성자) 를 통해 할당

  • delete (포인터명)를 통해 메모리 해제

  • 작동 원리

    • new int(5)에서 메모리 상에 int형을 저장하는 공간이 생기고 5가 저장됨

    • 새로 생긴 공간의 주소값이 a에 저장됨

배열의 동적할당

  • 기본적으로 배열의 경우 컴파일 시간에 크기가 결정됨

  • 동적할당을 통해 배열의 크기를 동적으로 정할 수 있다

// 동적할당을 사용하지 않으려면 int arr[1000]; 처럼 넉넉히 할당해야 함
#include <iostream>

using namespace std;

int main(void) {
    int *arr;
    int len;
    cout << "동적할당할 배열의 길이 입력: ";
    cin >> len;
    arr = new int[len];  // int(5), int[len] 이런 차이.
    for (int i = 0; i < len; i++) {
        arr[i] = len - i;
    }
    for (int i = 0; i < len; i++) {
        cout << arr[i] << endl;
    }

    delete[] arr;  // delete arr하면 배열 첫번째 칸만 삭제됨.
}
  • 주의점 : 동적할당된 배열의 메모리를 해제하려면 delete가 아닌 delete[] 를 사용해야 함

객체의 동적할당

#include <iostream>
using namespace std;

class Vector2 {
   public:
    Vector2() : x(0), y(0) {
        cout << this << " : Vector2()" << '\n';
    }
    Vector2(const float x, const float y) : x(x), y(y) {
        cout << this << " : Vector2(float x, float y)" << '\n';
    }

    ~Vector2() {
        cout << this << " : ~Vector2()" << '\n';
    }

    float GetX() const {
        return x;
    }
    float GetY() const {
        return y;
    }

   private:
    float x;
    float y;
};

// 직접 실행하여 생성과 소멸 순서 알아보기
int main(void) {
    Vector2 s1 = Vector2();
    Vector2 s2 = Vector2(3, 2);
    Vector2 *d1 = new Vector2();
    Vector2 *d2 = new Vector2(3, 2);

    cout << "(" << d1->GetX() << ", " << d1->GetY() << ")" << '\n';
    cout << "(" << d2->GetX() << ", " << d2->GetY() << ")" << '\n';
    delete d1;
    delete d2;
}
  • 동적할당된 변수들이 먼저 소멸되고, s1, s2가 그 다음 소멸된다.

  • 소멸은 선언의 역순이기도 함.

참조) 두들낙서 C/CPP 강의