M
mathieu
Hello,
I would like implement a nice way to work around the array of
references issue in C++. What do usually people do ? Do you maintain a
separate factory/pool of elements as part of the API ?
So in my example (*) I would need to either :
1. allocate on the heap (and then fragment memory):
void fill(A *array[])
{
A *a = new A;
B *b = new B;
array[0] = a;
array[1] = b;
}
or have a mechanism that store elements of the same type in individual
arrays:
A PoolA[100];
B PoolB[100];
void fill(A *array[])
{
A *a = GetNextFromPoolA()
B *b = GetNextFromPoolB();
array[0] = a;
array[1] = b;
}
GetNextFromPoolA/B look like very complex tasks to implement. Does this
correspond to any known design pattern ?
Comments suggestion very welcome !
Mathieu
(*) Small dumb demonstration of problem:
#include <iostream>
struct A {
virtual void foo() {
std::cout << "A" << std::endl;
}
};
struct B : public A {
virtual void foo() {
std::cout << "B" << std::endl;
}
};
void fill(A *array[])
{
A a;
B b;
array[0] = &a;
array[1] = &b;
}
int main()
{
const int size = 2;
A* array[size]; // Have to use pointers...
fill(array);
for(int i=0; i<size;++i) {
array->foo();
}
return 0;
}
I would like implement a nice way to work around the array of
references issue in C++. What do usually people do ? Do you maintain a
separate factory/pool of elements as part of the API ?
So in my example (*) I would need to either :
1. allocate on the heap (and then fragment memory):
void fill(A *array[])
{
A *a = new A;
B *b = new B;
array[0] = a;
array[1] = b;
}
or have a mechanism that store elements of the same type in individual
arrays:
A PoolA[100];
B PoolB[100];
void fill(A *array[])
{
A *a = GetNextFromPoolA()
B *b = GetNextFromPoolB();
array[0] = a;
array[1] = b;
}
GetNextFromPoolA/B look like very complex tasks to implement. Does this
correspond to any known design pattern ?
Comments suggestion very welcome !
Mathieu
(*) Small dumb demonstration of problem:
#include <iostream>
struct A {
virtual void foo() {
std::cout << "A" << std::endl;
}
};
struct B : public A {
virtual void foo() {
std::cout << "B" << std::endl;
}
};
void fill(A *array[])
{
A a;
B b;
array[0] = &a;
array[1] = &b;
}
int main()
{
const int size = 2;
A* array[size]; // Have to use pointers...
fill(array);
for(int i=0; i<size;++i) {
array->foo();
}
return 0;
}