Re: Length of C++ arrays allocated by operator new[]
Noah Roberts <roberts.noah@gmail.com> wrote in news:74a0f16a-95f8-4b9c-
9e30-e4d868be2df5@t30g2000prm.googlegroups.com:
On Aug 27, 1:35?pm, Gerald Breuer <Gerald.Bre...@Use-Author-Supplied-
Address.invalid> wrote:
The length of the allocated array must be stored somewhere
by new so that delete[] knows how many destructors to call.
But theres no standard way to get this length.
That is not completely correct. You can override the new operator to
use an allocator that will provide you with that information. This
would all indeed be quite within the standard. It is also, of course,
why there can never be a *generic* method of accessing this
information.
It's not so trivial. The argument the operator new[] is called with does
not specify the number of objects; it specifies the number of bytes to
allocate. This can include unknown amount of extra memory used by the
implementation, which most probably varies for different types and can in
principle vary for each invocation. Demo:
#include <iostream>
class A {
public:
void *__cdecl operator new[](size_t n) {
std::cout << "A::operator new: n=" << n << ", overhead=" << n-
100*sizeof(A) <<" bytes\n";
return ::operator new[](n);
}
~A() {}
};
class B {
public:
void *__cdecl operator new[](size_t n) {
std::cout << "B::operator new: n=" << n << ", overhead=" << n-
100*sizeof(B) <<" bytes\n";
return ::operator new[](n);
}
~B() {}
private:
double x;
};
class C {
public:
void *__cdecl operator new[](size_t n) {
std::cout << "C::operator new: n=" << n << ", overhead=" << n-
100*sizeof(C) <<" bytes\n";
return ::operator new[](n);
}
private:
double x;
};
int main() {
A* a = new A[100];
B* b = new B[100];
C* c = new C[100];
}
--- output ---
A::operator new: n=104, overhead=4 bytes
B::operator new: n=808, overhead=8 bytes
C::operator new: n=800, overhead=0 bytes