运算符新[]和非POD类型
operator new[] and non POD types
我正在尝试超载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;
}
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 指向 POD 类型的指针之间的静态转换与重新解释转换
- 约束类模板函数以接受特定的 POD 类型
- POD类型是否完全等同于琐碎的标准布局类型
- 如何创建非 POD 类型的连续内存池?
- 避免在禁用复制的 POD 类型的内存上使用"-Wclass-memaccess"
- C++11 按 POD 类型的值传递比常量引用差
- POD 类型的二进制 I/O 如何不违反别名规则
- POD 类型的原子按位操作
- C 容器用于异质POD类型
- 检测Sfinae POD类型的第一成员
- POD类型作为结构的代理
- POD 类型是否可以具有显式声明的默认移动分配运算符
- 阅读和比较POD类型的填充字节是不确定的行为吗?
- 在英特尔上自然对齐的POD类型的保证原子操作
- 为什么具有已删除复制构造函数的结构不是 POD 类型
- 构造函数初始化列表中POD类型的初始化
- 使用初始化列表的 POD 类型初始化不起作用
- 移动 POD 类型的语义
- 非 pod 类型的布局(因为具有默认构造函数)