Pure Software Engineer :)
[C++] new operator 본문
new operator는 사용자가 overriding 해서 사용할 수 있다.
하지만 new.cpp에 보니 함수가 다음과 같은 형태로 되어있었다.
1 2 3 | void * operator new(size_t cb) { ... } |
그럼 저기서 size_t는 어디서 온다는 말일까?
보통 new 를 사용할 때 보면 다음과 같이 사용하는데...
1 | int * a = new int; |
찾아보니...한가지 잊었던 점이 있었다.
new는 함수가 아니라 operator 였단걸!!
결국 new operator 가 하는 일은 2가지로 볼 수 있는데.
1. 타입을 알아내서(sizeof(t) 를 통해) operator new 함수 호출.
2. 해당 객체의 생성자 호출.
그렇기 때문에 operator new 함수의 첫번째 매개변수는 size_t가 오는 것이었다!!.
또한 찾아보다가 placement new 라는것이 있는데,
이것은 사용자가 미리 메모리를 할당하고 해당 주소를 new operator 에게 넘겨주면
new operator가 하던 1번째 operator new 함수에서 heap_alloc을 하지 않는것이다.
이는 사용자가 메모리를 좀더 효율적으로(pooling을 통해) 관리할 수 있는 여지를 만들어주는것 같다.
해당 operator new 함수는 <new> 에 정의 되어 있으며 코드는 다음과 같다.
1 2 3 4 5 6 7 8 9 10 11 | #ifndef __PLACEMENT_NEW_INLINE #define __PLACEMENT_NEW_INLINE inline void *__CRTDECL operator new(size_t, void *_Where) _THROW0() { // construct array with placement at _Where return (_Where); } inline void __CRTDECL operator delete(void *, void *) _THROW0() { // delete if placement new fails } #endif /* __PLACEMENT_NEW_INLINE */ |
즉, 아무것도 하지 않고 그저 해당 메모리의 주소를 반환한다.
또 하나 주의할 점은 사용자는 operator placement new를 overriding 할 수 없다는 것이다.
위의 헤더에 보면 __PLACEMENT_NEW_INLINE 를 define 하고 있는데
overriding 하고 싶다면 아래와 같이 하면 될것이다.
1 2 3 4 5 6 7 | #ifndef __PLACEMENT_NEW_INLINE #define __PLACEMENT_NEW_INLINE inline void * __cdecl operator new (size_t bytes, void * ptr) { } .. ... #end // # ifdef __PLACEMENT_NEW_INLINE |
The correct answer is you cannot replace operator placement new.
§18.4.1.3 Placement forms
These functions are reserved, a C++ program may not define functions that displace the versions in the Standard C++ library.
references
http://www.cprogramming.com/tutorial/operator_new.html
http://stackoverflow.com/questions/3675059/how-could-i-sensibly-overload-placement-operator-new
http://stackoverflow.com/questions/4638429/c-placement-new-vs-overloading-new
http://msdn.microsoft.com/en-us/library/kewsb8ba(v=vs.71).aspx
'Software Engineering' 카테고리의 다른 글
Docker image로 Redis Cluster 쉽게 실행하기 (0) | 2023.03.20 |
---|---|
VI에서 swift syntax highlight 하는 방법 (0) | 2015.07.26 |
[MongoDb] Command (0) | 2014.12.23 |
[Redis] Redis data structure (0) | 2014.11.20 |
Google App Engine 'Hello world' using python SDK (0) | 2013.08.10 |