For Programmers: Free Programming Magazines  


Home > Archive > VC Language > January 2006 > Re: Overloading new









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: Overloading new
maynard

2006-01-25, 7:23 pm


Victor Bazarov wrote:
>
> MyClass* arrayCreator(size_t howmany, int argument) {
> char *storage = new char[howmany * sizeof(MyClass)];
> for (int i = 0; i < howmany; ++i)
> new (storage + sizeof(MyClass) * i) MyClass(argument);
> return reinterpret_cast<MyClass*>(storage);
> }
>


Not that it really matters, but I thought I'd let you guys know I got
it figured out. It took me a while, but for good reason. In my
implementation, the MyClass class is a class that was written by
somebody else. I (as a bad user) assumed this class had been fully
tested...I was, of course, wrong. The constructor MyClass(argument)
incorrectly attempts to initialize "this" by explicitly calling another
constructor (MyClass(arg1, arg2)), like this:

class MyClass
{
MyClass();
MyClass(int);
MyClass(int, int);
};

MyClass::MyClass()
{...}

MyClass::MyClass(int i)
{
MyClass::MyClass(0, i);
}

MyClass::MyClass(int j, int i)
{...}

So when the call to the placement new initializes storage with
MyClass(argument), the new object doesn't actually get initialized (a
local copy of a MyClass object within the single argument constructor
gets initialized...then destroyed). So I was getting unitialized
results with the code Victor had supplied. I've corrected it, and it
now works as desired.

Thanks again guys!

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com