(C++)10장-1. 동적메모리 관리, 스마트 포인터

int *age;
delete age;

char* name;
delete[] name;


<C언어와 C++의 동적메모리 비교>

1. C언어
char* name=(char*)malloc(sizeof(char)*10);
int* age=(int*)malloc(sizeof(int));
free(name);
free(age);


2. C++
char* name=new char[10];
int* age=new int;
delete[] name;
delete age;


<객체를 동적메모리에 할당>

C의 malloc(),free()는 C++의 new, delete와 차이가 있다.

예)Chulsoo* chulsooPtr1=(Chulsoo*)malloc(sizeof(Chulsoo));
 chulsooPtr1->setAge(32);
 chulsooPtr1->introduce();

 free(chulsooPtr1);
return 0;

--------------->객체의 생존주기에 빠질 수 없는 생성자와 소멸자가호출되지 않는다.
반면에,

Chulsoo* chulsooPtr1=new Chulsoo(32);
chulsooPtr1->introduce();

delete chulsooPtr1;
return 0;

-------------------->생성자와 소멸자가 호출 된다.

3. 스마트 포인터

int main(void)
{
  Chulsoo* chulsooPtr2=new Chulsoo(32);
  chulsooPtr2->introduce();
  delete chulsooPtr2;

 auto_ptr<Chulsoo> chulsooSmptr(new Chulsoo(32));
}

스마트포인터 auto_ptr를 이용한 동적 메모리 할당에서는 개발자가 따로 delete를 하지 않아도 소멸자를 호출하면서 항당된 동적 메모리르 해제한다.

이것이 스마트포인터의 장점이다. 즉, 스코프(scope)를 벗어난 로컬 변수가 자동 소멸하듯이 스코프를 벗어난 동적변수도 스마트포인터를 활용하여 자동 소멸 한다.



3.1  auto_ptr

가리키는 객체에 대한 소유권을 강조한다.
예)

int main(void)
{
 auto_ptr<Chulsoo> chulsooSmptr1(new Chulsoo(32));
 chulsooSmptr1->introduce();
cout<<"auto_ptr<Chulsoo> 타입간 복사 생정자 호출 후"<<endl;
auto_ptr<Chulsoo> chulsooSmptr2=chulsooSmptr1;
chulsooSmptr1->introduce();
chulsooSmptr2->introduce();
}
//에러 발생 4번 줄이 의미하는것은 chulsooSmptr1이 가리키는 객체를 chulsooSmptr2가 가리키게 하는 것이다. auto_ptr이 가리키는 동적객체는 항상 한개이어야 한다.
따라서 chulsooSmptr1은 null포인터를 가리키게 된다.

3.2 unique_ptr

unique_ptr은 auto_ptr과 유사하게 가리키는 객체의 소유권을 그대로 강조하지만, 이전 예제처럼 런타임에서 오류가 발생하지 않고, 컴파일러가 오류를 잡아서 심각한 문제도 발생치 않는다.
int main(void)
{
 unique_ptr<Chulsoo> chulsooSmptr1(new Chulsoo(32));
 chulsooSmptr1->introduce();

 unique_ptr<Chulsoo> chulsooSmptr2=chulsooSmptr1;
 chulsooSmptr1->introduce();
 chulsooSmptr2->intoduce();
}

3.3 shared_ptr

하나의 동적객체를 여러개의 스마트포인터로 가리키길 원할 수 있다.

int main(void)
{
 shared_ptr<Chulsoo> chulsooSmptr1(new Chulsoo(32));
 chulsooSmptr1->introduce();

 shared_ptr<Chulsoo> chulsooSmpt2=chulsooSmptr1;
}


--->>>>>하나의 객체를 여러 스마트 포인터가 가리키게 하고, 여러 스마트 포인터가 가리키는 객체를 해제할 때 중복해제 되는 문제가 있지 않은가 의문을 가질 수 있다.
이러한 문제를 shared_ptr는 레퍼런스 카운팅기법으로 해결한다.
즉 레퍼런스카운팅은 특정한 동적객체를 가리키는 스마트포인터가 몇개가 생성되었는지 카운팅 한다. 카운팅이 0에 도달하면 마지막 스마트 포인터가 수명이 다했을때 소멸자를 호출하여 동적객체를 해제한다.

댓글

이 블로그의 인기 게시물

(네트워크)폴링방식 vs 롱 폴링방식

(ElasticSearch) 결과에서 순서 정렬

(18장) WebSocekt과 STOMP를 사용하여 메시징하기