ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 동적 메모리 할당(malloc, new)
    플밍/C++ (overview) 2012. 1. 3. 22:47
    2006/07/29 02:07




    [C style]

     

    int* arr = (int*) malloc (sizeof(int) * size);

    free arr;

     

    [C++ style]

     

    <사용 예>

     

    int* arr = new int;         // 하나의 공간 선언할때

    delete arr;

     

    int* arr = new int[size];     // 배열 선언할때

    delete[] arr;

     

    ==========================================================

     

    <new 연산자는 목적을 달성 못했을때 NULL 포인터를 리턴한다>

     

    할당할 공간이 부족하면, NULL포인터를 리턴한다.

     

    NULL포인터란 정수 0을 의미한다. (NULL = 0 바꿔써도 상관없다.)

     

    또는 exception을 발생시키는데,

     

    catch(bad_alloc xx) {...}

     

    와 같이 사용하면 된다.

     

    ==========================================================

     

    <malloc와 new의 차이점>

     

    When new is used to allocate memory for a C++ class object,

    the object's constructor is called after the memory is allocated.

     

    malloc은 단순히 지정한 type의 메모리 공간을 할당해 주는것이 하는일의 전부이다.

    그러나, new는 객체 type에 대해 쓰였을때, 공간을 할당해 줄뿐만 아니라,

    그러고나서 그 객체의 생성자를 함께 호출해주는일까지 한다.

     

    이로써 new는 객체 생성과 동시에 초기화라는 목적에 잘 부합한다.

    '플밍 > C++ (overview)' 카테고리의 다른 글

    정보은닉(information hiding), 캡슐화  (0) 2012.01.03
    구조체에서 클래스로!  (0) 2012.01.03
    레퍼런스(&) , call-by-reference  (0) 2012.01.03
    const, * ..  (0) 2012.01.03
    namespace, (범위지정연산자)  (0) 2012.01.03
Designed by Tistory.