| maynard 2006-01-24, 7:07 pm |
|
Victor Bazarov wrote:
>
> You're most welcome!
>
> Take a look how 'std::vector' does that. It uses "placement new" to
> create and copy all those elements when it needs to reallocate. You need
> to do the same thing, most likely:
>
> #include <memory>
>
> class SomeOtherClass {
> int i;
> public:
> SomeOtherClass(int i) : i(i) {}
> int get() const { return i; }
> };
>
> class MyClass : public SomeOtherClass {
> public:
> MyClass(int i) : SomeOtherClass(i) {}
> };
>
> 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);
> }
>
> void arrayDisposer(MyClass* arr)
> {
> delete[] reinterpret_cast<char*>(arr);
> }
>
> int main() {
> MyClass *myArray(arrayCreator(100, 42));
> int a = myArray[77].get();
> arrayDisposer(myArray);
> }
>
> V
That looks to be exactly what I need to do. I'll give it a try.
|