2013년 10월 2일 수요일

Boost 라이브러리의 스마트 포인터

c++에서 배열을 사용할 때는 할당과 함께 해제를 해야 한다.  해제가 안되면 메모리 누수를 일으킨다.
스마트 포인터를 활용하면 해제가 따로 필요하지 않아 코딩이 편해 진다. 특히 class를 만들 때 내부의 동적 메모리를 다루기가 편리하다.
아래는 boost의 smart pointer를 이용한 객체 및 메모리 할당을 보여준다.

// Boost smart Pointer
//
#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include "boost/smart_ptr/shared_ptr.hpp"


using namespace std;
class Fruit
{
public:
Fruit(string name);
~Fruit();
string GetName() { return name; }
private:
string name;
typedef boost::shared_ptr<int> f_ptr;
f_ptr fa;

};

Fruit::Fruit(string name)
{
this->name = name;
cout << this->name + "생성됨" << endl;
fa = f_ptr(new int [100]);
int *vv = fa.get();
for(int i=0; i<100; i++) vv[i] = i;
}

Fruit::~Fruit()
{
int *vv = fa.get();
for(int i=0; i<3; i++) cout << vv[i] <<" ";
cout << name+"소멸됨" << endl;
}

void main()
{
typedef boost::shared_ptr<Fruit> fruit_ptr;
vector<fruit_ptr> vec;

fruit_ptr s = fruit_ptr(new Fruit("Apple"));
vec.push_back(fruit_ptr(new Fruit("Pear")));
vec.push_back(fruit_ptr(new Fruit("Banana")));
vec.push_back(fruit_ptr(new Fruit("Kiwi")));
vec.push_back(s);

cout << endl << (*s).GetName() << endl << endl;

fruit_ptr p0 = vec[0];

}

* 실행 결과



댓글 2개: