Re: Overloading new[]
- From: Victor Bazarov <v.Abazarov@xxxxxxxxxxxx>
- Date: Tue, 24 Jan 2006 14:31:53 -0500
maynard wrote:
I'm attempting to overload the new[] operator. This is my first attempt at doing so, but I've found quite a few articles to help me out. Here is the source for my overloaded operator new[]:
class myClass { public: myClass(); ~myClass(); void *operator new[](size_t, long); protected: double *v1; double *v2; long num_pts; };
myClass::myClass() { //ctor... }
myClass::~myClass() { //dtor... }
void *myClass::operator new[](size_t sz, long numpts) {
Have you seen what 'sz' is before you scale it down?
sz /= sizeof(myClass);
I am not sure why but you actually lose a chunk of your array here.
myClass *x = ::new myClass[sz];
I don't think you're supposed to do that here. You're supposed to allocate a char array of size 'sz' (without dividing it) and then just return it.
for(size_t j = 0; j < sz; j++){ x[j].v1 = new double[numpts]; x[j].v2 = new double[numpts]; for (long i=0;i<numpts;++i){ x[j].v1[i] = 0.; x[j].v2[i] = 0.; } x[j].num_pts = numpts; } return x; }
I pass the "message" as follows:
int numObjs = 100; long totalPts = 100000; myClass* myObj = new(totalPts) myClass[numObjs];
When I step through this in the debugger (MS VC++ .NET), it appears that the local "x" (in operator new[]) is properly allocated and initialized. However, when it returns, myObj isn't. I also noticed in the debugger that the memory location for "x" is 0x00321714, but myObj (after new[] returns) is 0x00321718.
With that said, two questions...have I properly defined & implemented my new[] operator? Is there a problem in the debugger??
I don't think you properly implemented it. Check out the following page http://www.codeguru.com/cpp/tic/tic0139.shtml
The system calls "new operator" that figures out the size (your 'sz') and
then calls "operator new[]", after which it takes the returned pointer and apparently adjusts it. You're not supposed to fiddle with the array
before "new operator" gives it back to your 'myObj'.
I understand *why* you wanted to do what you did. You just tried doing it at the wrong time...
V .
- Follow-Ups:
- Re: Overloading new[]
- From: maynard
- Re: Overloading new[]
- References:
- Overloading new[]
- From: maynard
- Overloading new[]
- Prev by Date: Overloading new[]
- Next by Date: Re: Overloading new[]
- Previous by thread: Overloading new[]
- Next by thread: Re: Overloading new[]
- Index(es):