Re: class method static variable same across isntances?
"Chris ( Val )" <chrisval@gmail.com> wrote in message
news:1191594611.671775.251940@57g2000hsv.googlegroups.com...
On Oct 5, 9:26 am, "Jim Langston" <tazmas...@rocketmail.com> wrote:
The output of the following program for me is:
Same
0 1 2
Which is what I want. I just want to confirm this is well defined
behavior,
that a static local variable to a class function/method is the same
instance
across classes.
#include <iostream>
#include <vector>
class Foo
{
public:
std::vector<int>& Data( )
{
static std::vector<int> EmptyData;
return EmptyData;
}
int Bar()
{
static int Val = 0;
return Val++;
}
};
[snip]
Have you thought about deriving from a common base class?
E.g:
class Common
{
static std::vector<int> EmptyData;
// ...
};
class Foo : public Common
{
// ...
If you want common functionality across all instances,
it might be worth looking into something like this.
It's actually used in a method to return a reference to a set using a form
of recursion.
class PartIndex
{
public:
PartIndex( const std::string& Name = "Torso" ): Name_( Name ) {}
// Lot of other public methods used to populate Indicies_ and Parts_
std::set<size_t>& PartIndicies( const std::string& Name )
{
static std::set<size_t> EmptySet;
EmptySet.clear();
if ( Name_ == Name )
{
return PartIndicies();
}
else
{
for ( std::vector<PartIndex>::iterator it = Parts_.begin(); it
!= Parts_.end(); ++it )
{
std::set<size_t>& ReturnSet = (*it).PartIndicies( Name );
if ( &ReturnSet != &EmptySet )
return ReturnSet;
}
return EmptySet;
}
}
private:
std::string Name_;
std::set<size_t> Indicies_;
std::vector<PartIndex> Parts_;
};
My other option would be to use a try...catch block which I am not fond of
for using for something like this.