我相信它会做新的[]知道什么构造函数调用同样的方式:编译器告诉它。编译器正在跟踪数据类型并知道它是否是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;
}
如何知道分配对象的大小? 'operator new'和'operator new []'都是以字节为单位给出的总大小,而不是单个结构的大小。我想这是没有好的解决方案的那些问题之一... – nimrodm
@nimrodm:我想我正在考虑每类运营商新。 –
@nimrodm:我刚刚添加的示例代码似乎适用于大于一个'size_t'的类。可能或可能不会帮助你。 –