我相信它會做新的[]知道什麼構造函數調用同樣的方式:編譯器告訴它。編譯器正在跟蹤數據類型並知道它是否是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'的類。可能或可能不會幫助你。 –