2014-01-29 54 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'的类。可能或可能不会帮助你。 –