me**********@virgilio.it wrote:
I'm in trouble with operator new:
I have overloaded it to track allocated memory, but what I really need
is to get constructor argument.
/////////////CODE:
class myClass {
public:
myClass(int n) { p = new int[n];}:
~myClass() {delete []p;}
int* p;
void* operator new( size_t stAllocateBlock );
};
/////////////ENDCODE
Then I call my own operator new:
myClass* point = new myClass ( 10 );
What I want is to know constructor argument inside operator new.
Is it possible or it's just a dream?
operator new doesn't see the constructor argument. Its job is to
allocate memory, and all it needs for that is the size of the thing that
it's allocating. You can define it to take additional arguments, though,
like this:
void *operator new(size_t size, int count);
and now when it's called you can do whatever you need to do with count.
But you have to use the somewhat funky placement syntax:
myClass *point = new (10) myClass(10);
Having to write that 10 twice is not a good idea, so you should add a
layer of indirection:
So what you need is an additional layer of indirection:
myClass *allocate_myClass(int n)
{
return new (n) myClass(n);
}
And now use that instead:
myClass *point = allocate_myClass(10);
--
-- Pete
Roundhouse Consulting, Ltd. (
www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (
www.petebecker.com/tr1book)