运算符新[]和非POD类型

operator new[] and non POD types

本文关键字:POD 类型 和非 运算符      更新时间:2023-10-16

我正在尝试超载operator new,以跟踪内存分配(用于调试)。分配非POD类型的数组时,我遇到了麻烦(例如,持有std :: string的类的数组)。

似乎 operator new被要求分配用于存储数组长度的数组 8个字节的内存(可能使编译器可以在数组被销毁时调用正确的数量破坏者数字)。

)。

operator new[]如何确定实际数据将放置在返回的地址(POD的数组)还是在返回的地址 8?(我需要这个,以便我可以搜索指针的结构)

我认为它将采取与新[]知道要称呼的构造函数相同的方式:编译器告诉它。编译器正在跟踪数据类型,并且知道何时是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") << " countedn";
    return ::operator new[](count, std::nothrow);
}
int main()
{
    A* pa = new A[16];
    B* pb = new B[16];
    return 0;
}