ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 동적 할당
    C++ 2021. 12. 23. 22:22

    https://www.youtube.com/watch?v=yOiBxEfYU9E&list=PLlJhQXcLQBJqywc5dweQ75GBRubzPxhAk&index=70

     

    1. 동적 할당

    정적할당 : int a; 같은걸로 프로그램이 실행되면 메모리를 차지하고 프로그램이 종료되면 사라진다.

    동적할당 : 프로그램 실행 중 변수를 메모리에 할당하는 것으로 원할 때 메모리를 확보하고 해제할 수 있음.

    동적할당을 사용할 땐 변수를 포인터로 선언해줘야한다.

     

    - 메모리 생성

     자료형 *변수명 = new 자료형();

     

    - 메모리 해제

    delete 변수명;

    #include <iostream>
    
    using namespace std;
    
    int main() {
    	int* a = new int(5);
    
    	cout << a << endl;
    	cout << *a << endl;
    
    	*a = 10;
    
    	cout << a << endl;
    	cout << *a << endl;
    
    	delete a;
    }

     

    2. 배열 동적 할당

    - 메모리 생성

    자료형* 변수명 = new int[배열의길이];

     

    - 메모리 해제

    delete[] 배열명;

     

    #include <iostream>
    
    using namespace std;
    
    int main() {
    	int len;
    	cout << "배열의 길이 입력 : ";
    	cin >> len;
    
    	int* a = new int[len];
    
    
    	for (int i = 0; i < len; i++)
    		a[i] = len - i;
    
    	for (int i = 0; i < len; i++)
    		cout << a[i] << ' ';
    	cout << endl;
    
    	delete[] a;
    }

     

    3. 객체 동적 할당

    - 객체 생성

    타입형 *변수명 = new 타입형();

     

    - 객체 소멸

    delete 변수명;

    #include <iostream>
    
    using namespace std;
    
    class Vector2 {
    public:
    	Vector2() : x(0), y(0) {
    		cout << this << " : Vector2()" << endl;
    	}
    
    	Vector2(const float x, const float y) : x(x), y(y) {
    		cout << this << " : Vecotr2(const float x, const float y)" << endl;
    	}
    
    	~Vector2() {
    		cout << this << " : ~Vector2()" << endl;
    	}
    
    	float GetX() { return x; }
    	float GetY() { return y; }
    
    private:
    	float x;
    	float y;
    };
    
    int main() {
    	Vector2 s1 = Vector2();
    	Vector2 s2 = Vector2(3, 2);
    
    	Vector2* d1 = new Vector2();
    	Vector2* d2 = new Vector2(3, 2);
    
    	cout << "d1->x : " << d1->GetX() << ", " << "d1->y : " << d1->GetY() << endl;
    	cout << "d2->x : " << d2->GetX() << ", " << "d2->y : " << d2->GetY() << endl;
    
    	delete d1;
    	delete d2;
    }

     

    정적으로 선언된 변수보다 동적으로 선언된 변수가 먼저 소멸된다.

    'C++' 카테고리의 다른 글

    String클래스와 파일 입출력 응용  (0) 2022.01.05
    깊은 복사와 얕은 복사 (1)  (0) 2021.12.24
    8부 (클래스) 종합문제 - 2  (0) 2021.12.23
    8부 (클래스) 종합문제 - 1  (0) 2021.12.23
    연산자 오버로딩  (0) 2021.12.23
Designed by Tistory.