2012-03-29 4 views
2

의 횟수 계산 new 연산자를 사용하는 방법 : ostringstream이 방법을 사용할 때 동적 메모리 할당의 횟수를 계산하려면다음 코드를 감안할 때 동적 메모리 할당

int i; 
... 
ostingstream os; 
os<<i; 
string s=os.str(); 

합니다. 어떻게해야합니까? 어쩌면 operator new을 통해?

감사합니다.

답변

5

네, 그리고 당신이 그것을 할 수있는 방법은 다음과 같습니다

내 환경 (우분투 10.4.3, g ++)에서
#include <new> 
#include <cstdlib> 
#include <iostream> 
#include <string> 
#include <vector> 
#include <sstream> 

int number_of_allocs = 0; 

void* operator new(std::size_t size) throw(std::bad_alloc) { 
    ++number_of_allocs; 
    void *p = malloc(size); 
    if(!p) throw std::bad_alloc(); 
    return p; 
} 

void* operator new [](std::size_t size) throw(std::bad_alloc) { 
    ++number_of_allocs; 
    void *p = malloc(size); 
    if(!p) throw std::bad_alloc(); 
    return p; 
} 

void* operator new [](std::size_t size, const std::nothrow_t&) throw() { 
    ++number_of_allocs; 
    return malloc(size); 
} 
void* operator new (std::size_t size, const std::nothrow_t&) throw() { 
    ++number_of_allocs; 
    return malloc(size); 
} 


void operator delete(void* ptr) throw() { free(ptr); } 
void operator delete (void* ptr, const std::nothrow_t&) throw() { free(ptr); } 
void operator delete[](void* ptr) throw() { free(ptr); } 
void operator delete[](void* ptr, const std::nothrow_t&) throw() { free(ptr); } 

int main() { 
    int start(number_of_allocs); 

    // Your test code goes here: 
    int i(7); 
    std::ostringstream os; 
    os<<i; 
    std::string s=os.str(); 
    // End of your test code 

    int end(number_of_allocs); 

    std::cout << "Number of Allocs: " << end-start << "\n"; 
} 

, 대답은 "2"입니다.


편집 : 새로운 운영자가 사용자 - 내장 타입, 클래스 형의 객체를 포함하지 않는 그 객체를 할당하는 데 사용되는 경우 MSDN

글로벌 연산자 새 함수를 인용가 호출된다 정의 된 연산자 새 함수 및 모든 유형의 배열이 있습니다. 새 연산자가 연산자 new가 정의 된 클래스 유형의 객체를 할당하는 데 사용되면 해당 클래스의 연산자 new가 호출됩니다. 클래스 operator new하지 않는

그래서 모든 새로운 표현은 글로벌 operator new를 호출합니다. 목록에있는 수업의 경우, 나는 반 수준이 없다고 믿는다. operator new.

+0

나는 본다. 따라서 '연산자 new'는 모든 동적 메모리 할당이 재정의 된 버전을 호출해야 할 필요가 있다는 점에서 전역 적입니다. 맞습니까? –

+0

최근 편집 내역보기 –

1

동적으로 할당 된 객체를 계산하려면 클래스에 대해 new 연산자를 오버로드하여 계산 논리를 추가해야합니다.

좋은 읽기 :
How should I write ISO C++ Standard conformant custom new and delete operators?

+0

전체 예제를 제공해 주실 수 있습니까? 감사! –

+1

@littleEinstein : 링크를 확인하십시오. –

+0

맞아요, 나는'operator new '가 어떻게 작동 하는지를 어느 정도 알고 있습니다. 그러나 나는 그것을'ostringstream'에 적용하는 방법을 모르겠습니다. 나는 필사적으로 구체적인 예를 필요로한다. :) –

0

리눅스 (glibc는)를 사용하는 경우, 당신은 모든 동적 메모리 할당을 기록 a malloc hook를 사용할 수 있습니다. 여기