Pointer Container, boost::ptr_vector<>

hared_ptr를 사용해서 vector에 값을 넣을때 다음과 같이 사용했었습니다.
v.push_back(boost::shared_ptr(new int(1)));
 대충 알고 써먹은 boost를 천천히 훑어보기로 맘먹고 보는데 Pointer Container라는 것이 있어서
간단하게 테스트하고 잊어버리기 전에 기록해둡니다.
class PtrTest
{
public:
	PtrTest() {value_ = 0;};
	~PtrTest() {};
	PtrTest(const PtrTest& other)
	{
		std::cout << "Copy Const" << std::endl;
		value_ = other.value_;
	}
	PtrTest& operator=(const PtrTest& rhs)
	{
		if(this == &rhs)
		{
			return *this;
		}
		std::cout << "= Operator" << std::endl;
		this->value_ = rhs.value_;		
		return *this;
	}	
	void SetValue(int value) {value_ = value;}
	int GetValue() {return value_;}
	
private:
	int value_;
};

TEST(PtrVectorTest, ptr_vector_test)
{
	boost::ptr_vector ptr_vector; 

	PtrTest* test_a = new PtrTest;
	test_a->SetValue(1);

	PtrTest* test_b = new PtrTest;
	test_b->SetValue(2);
	
	ptr_vector.push_back(test_a); 
	ptr_vector.push_back(test_b); 
	ptr_vector.push_back(new PtrTest); 

	PtrTest* test_ptr = &ptr_vector[0];	
	EXPECT_EQ(1, test_ptr->GetValue());

	PtrTest test_ptr_2 = ptr_vector[1];	
	EXPECT_EQ(2, test_ptr_2.GetValue());
	EXPECT_EQ(3, ptr_vector.size());

	ptr_vector.erase(ptr_vector.begin());
	EXPECT_EQ(2, ptr_vector.size());
}


new한 데이터를 boost::ptr_vector에 넣고 나서 delete를 하지 않아도 메모리릭이 발생하지 않습니다.
boost::ptr_vector 내부적으로 메모리 관리를 하고 있는듯합니다.
이부분은 내부 동작을 좀더 자세히 살펴봐야 알 수 있을 듯합니다.

boost::ptr_vector를 사용하기 위해서는 boost/ptr_container/ptr_vector.hpp 를 include 해야 합니다.

boost::ptr_vector 말고도 boost::ptr_deque, boost::ptr_list, boost::ptr_set,
boost::ptr_map, boost::ptr_unordered_set, boost::ptr_unordered_map이 더 있다고 합니다.

출처 -  http://en.highscore.de/cpp/boost/smartpointers.html 




'프로그래밍' 카테고리의 다른 글

기본 생성자와 생성자 오버로딩  (0) 2012.09.08
eclipse에 pydev 설정 에러 처리  (0) 2012.06.18
Office Add-in 만들기.  (0) 2012.02.08
Lua 테이블 내용 출력하기  (0) 2012.01.28
Lua Table 복사에 대한 처리  (0) 2012.01.16