By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,562 Members | 1,307 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,562 IT Pros & Developers. It's quick & easy.

operator new and constructor argument

P: n/a
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

Feb 8 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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)
Feb 8 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.