Enum count 가져오기

Enum으로 정의된 것을 for문으로 돌려야 할 경우가 있는데 갯수를 가져오기 편한 방법이 있다.

아래와 같이 마지막에 count를 정의를 해놓고,

typedef enum {
    GenderMale   = 0,
    GenderFemale = 1,
    
    GenderCount
} Gender;

for문에서 가져와서 쓸 때는 아래와 같이 쓰면 된다.


 NSMutableArray *genders = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < GenderCount; ++i)
    {
        [genders addObject:[ModelTypeConstant stringWithGender:(Gender)i]];
    }

C++ Smart Pointer

Cocos2d-x autorelease pool에 대한 글을 보다가 알게 된 smart pointer..

C++11 부터 지원이 되는 것 같은데, 자동으로 메모리 해제를 지원해 주는 것 같다.
종류는 shared_ptr, unique_ptr, weak_ptr 가 있고, shared_ptr이 objective-c 메모리 관리할 때 사용하는 reference count 개념이랑 비슷하게 동작하는 것 같다. (필요할 때 count가 올라가고, 필요없을 때 count가 하나 줄어들고, count가 0일 때 해제하는 방식)

cocos2d-x autorelease pool도 shared_ptr 방식을 이용해서 구현 한 모양인데, 좀 더 자세한 내용은 레퍼런스를 봐야할 듯 싶다.

참조
http://en.wikipedia.org/wiki/Smart_pointer
http://zilongshanren.com/blog/2013/12/20/what-is-autorelease-pool/

calloc vs malloc

정리하자면  malloc은 사이즈만큼 메모리를 할당하고, calloc은 어떤 사이즈의 요소들이 몇개 있는지 넘겨서 그만큼 메모리 영역을 할당하는 식으로 사용한다.

calloc() 문법

void *calloc(size_t nelements, size_t bytes);

또 calloc은 메모리를 할당할때, 0으로 초기화가 된다.

calloc(m, n)을 malloc() 할당한다면 아래와 같다. (calloc이 할당될 때 0으로 초기화 되기 때문에, memset() 까지 사용한 것과 같아진다.)

p = malloc(m * n); 
if(p) memset(p, 0, m * n);

참조 링크 : http://www.diffen.com/difference/Calloc_vs_Malloc

Union

기억이 안나서, 오랜만에 찾아본..

1. Union (공용체)

Union은 구조체랑 문법이 비슷하고, 사용법도 비슷하지만 주소를 공유하냐 안하냐의 차이를 가지고 있다.

예를들어,

struct {int a; short b}

구조체는 메모리를 [a | b] 이렇게 int 4바이트, short 2 바이트를 차지를 한다.

하지만,

union {int a; short b}

공용체는 가장 큰 메모리인 int 4바이트를 차지한다.
[  a  ]
[ b   ]

참조 : http://en.wikipedia.org/wiki/Union_type

2. 사용하는 경우

보통 같은 값이지만, 타입을 바꿔서 사용할 경우에 자주 사용한다고 한다.

union
 {
 int i;
 float f;
 } u;
// Convert floating-point bits to integer:
 u.f = 3.14159f;
 printf("As integer: %08x\n", u.i);

출처 : http://stackoverflow.com/questions/252552/why-do-we-need-c-unions