2014-01-29 56 views
4

我想爲了跟蹤內存分配(調試)超載operator new。在分配非POD類型的數組時(例如,存放std :: string的類的數組),我遇到了麻煩。運營商新的[]和非POD類型

看起來好像調用operator new爲數組+8字節分配內存用於存儲數組長度(可能使編譯器可以在數組被銷燬時調用正確數量的析構函數)。

operator new[]如何找出實際的數據是否將被放置在返回地址(莢果的陣列)或在返回的地址+ 8? (我需要這個,這樣我可以搜索結構的指針)

回答

1

我相信它會做新的[]知道什麼構造函數調用同樣的方式:編譯器告訴它。編譯器正在跟蹤數據類型並知道它是否是POD類型。

但你真正的問題不在於如何運營商新的[]知道或編譯器是如何知道,但你怎麼能找出來。

如果您分配的對象不是大小8然後通過新的請求的任何大小[]是一個不能用的sizeof(對象)整除將包括對象的個數。這可能對你有用。

以下代碼類似乎工作。我相信有很多方法可以打破它。

#include <new> 
#include <iostream> 

using namespace std; 

class A { 
    int x; 
    int y; 
}; 

class B { 
    int x; 
    int y; 
    static int count; 
public: 
    B() : x(0), y(0) { ++count; } 
    ~B() { --count; } 
}; 

int B::count = 0; 

template<class T> 
T gcd(T a, T b) 
{ 
    T tmp; 
    while(b) { 
     tmp = a % b; 
     a = b; 
     b = tmp; 
    } 
    return a; 
} 

void* operator new[](size_t count) 
{ 
    size_t r = gcd(count, sizeof(size_t)*2); 
    bool is_counted = r == sizeof(size_t); 
    cout << count << " bytes requested and gcd is " << r << ' ' << (is_counted ? "is" : "is not") << " counted\n"; 
    return ::operator new[](count, std::nothrow); 
} 

int main() 
{ 
    A* pa = new A[16]; 
    B* pb = new B[16]; 
    return 0; 
} 
+0

如何知道分配對象的大小? 'operator new'和'operator new []'都是以字節爲單位給出的總大小,而不是單個結構的大小。我想這是沒有好的解決方案的那些問題之一... – nimrodm

+0

@nimrodm:我想我正在考慮每類運營商新。 –

+0

@nimrodm:我剛剛添加的示例代碼似乎適用於大於一個'size_t'的類。可能或可能不會幫助你。 –