Re: how to "save" memory on creating array of class with virtual
function
* dbtouch:
On Feb 17, 8:04 pm, "Alf P. Steinbach" <al...@start.no> wrote:
* dbtouch:
Dear C++ Users,
I was facing a challenge in my application: we have a class, say,
CFoo, with virtual function. We need create a large a array of CFoo in
the application, CFoo array[10000]. Because of vptr of CFoo, we ended
up with 80000 bytes memory to store vptrs. Is there a better way in
design or technically to save memory while keeping the ploymorphism? I
can only think of using function pointer instead.
You might consider the FlyWeight pattern.
Essentially, separate state and functionality, bring the functionality to the state.
In array store only state.
> Hi, Alf
>
> So I can implement CFoo like:
>
> class FuncCFoo {
> public:
> virtual void work();
> };
>
> class CFoo {
> int m_data;
> //... all the state data
> static FuncCFoo* ptr; // pointer points to FuncCFoo which is a base
> class of CFoo functionality
> public:
> void work() {
> ptr->work();
> }
> };
>
> In this case, I only add 8 bytes. Any comments?
First, please don't top-post -- see the FAQ.
Regarding the technical, I'm not sure what the above is meant to achieve. On the
face of it the "static" pointer seems to mean that you want a polymorphic
instance of FuncCFoo associated with the /type/ CFoo. I don't understand why.
Anyways the 'ptr->work()' call would have to pass a reference to the state.
Consider perhaps something simpler like a very strong known-at-compile time
association between state and functionality classes,
class Foo
{
public:
class State
{
};
virtual void work( State& aState ) const {}
};
class Bar: public Foo
{
public:
virtual void work( State& aState ) const {}
};
int main()
{
std::vector<Foo::State> v;
v.push_back( Foo::State() );
for( size_t i = 0; i < v.size(); ++i ) { Bar().work( v.at( i ) ); }
}
I've not focused very much on type constraints here since I don't know what
constraints you'd want, but presumably there is a class corresponding to "Bar"
(otherwise the virtual routine wouldn't be an issue), and presumably it doesn't
add state or add anything to the class invariant, just a specialization of the
processing?
Cheers & hth.,
- Alf