본문 바로가기
Programming/C & C++

해깔리는 STL resize() 와 reserve()에 대한 고찰

by leanu 2009. 9. 21.
상황 : 할당하고자 하는 메모리영역은 현재 잡힌 것보다 크다.

resize(n) : 메모리를 할당. 오브젝트 하나를 생성한 후, 크기가 일치할때까지 오브젝트를 계속 삽입힌다.

reserve(n) : 메모리를 할당. 끝

size() : 컨테이너 내부의 실제 오브젝트 갯수

capacity() : 할당된 메모리 총 영역 ( 컨테이너에 들어갈 수 있는 오브젝트의 총 갯수 )

아래의 소스를 보자.

결과

Resize Test ----------------
0th class is created 0x7fff63076400
1th class is copied from 0x7fff63076400 to << 0x17a0a90
2th class is copied from 0x7fff63076400 to << 0x17a0a94
3th class is copied from 0x7fff63076400 to << 0x17a0a98
Destructor : 0x7fff63076400
4th class is created 0x7fff630763f0
5th class is copied from 0x17a0a90 to << 0x17a0ab0
6th class is copied from 0x17a0a94 to << 0x17a0ab4
7th class is copied from 0x17a0a98 to << 0x17a0ab8
8th class is copied from 0x7fff630763f0 to << 0x17a0abc
Destructor : 0x17a0a90
Destructor : 0x17a0a94
Destructor : 0x17a0a98
Size : 4 Capacity : 6

Reserve Test ----------------
9th class is copied from 0x7fff630763f0 to << 0x17a0a90
Size : 1 Capacity : 3 
Destructor : 0x7fff630763f0
Destructor : 0x17a0a90
Destructor : 0x17a0ab0
Destructor : 0x17a0ab4
Destructor : 0x17a0ab8
Destructor : 0x17a0abc



Resize를 한경우 copy constructor 가 (resize 크기 - 이전 크기)만큼 일어나며, 그에 따라 size도 커짐을 알 수 있다.

Reserve를 한경우 capacity에만 영향을 미치고 size() 에는 영향을 주지 않음을 알 수 있다.

'Programming > C & C++' 카테고리의 다른 글

gdb 에서 signal 무시하기  (0) 2010.01.06
gcc 4.3 포팅시 유의할 점  (1) 2009.09.29
operator== issue in inheritance  (0) 2009.09.10
operator == in std::pair  (0) 2009.09.10
istream operator >> overriding into template class  (0) 2009.07.31

댓글