operator new and constructor argument

M

mente_fredda

Hi
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?

please answer me. Thanks
 
P

Pete Becker

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,079
Latest member
ElidaWarin

Latest Threads

Top