Re: Question about a static vector<*A> in class A
On 25 ec, 10:49, Jojo <no_m...@thanx.com> wrote:
I have a code like (just some illustrative lines, many things are omitted):
class string_interpreter {
static std::vector<* string_interpreter> my_vector;
*string_interpreter init(const string& s);
... // There's an "operator =" also, and ctor, dtor.
};
*string_interpreter string_interpreter::init(const string& s)
{
// Look in the vector if string 's' was already interpreted.
for (int i = 0; i < vector.length(); ++i)
if (//string 's' is already interpreted)
return vector[i]; // return the result of the interpretation
// Not in the vector, do string interpretation. Store results in the
// class's properties.
...
// Save results in the vector and return.
string_interpreter *new_interpreted_string = new string_interpreter;
*new_interpreted_string = *this;
my_vector.push_back(new_interpreted_string);
return new_interpreted_string;
}
So, basically this class accepts a string, interprets it and stores the
results in its own properties. Then the class makes sure that every
interpreted string (and its results, all within the class itself) is
stored in a vector to ensure that a string needs be interpreted only once.
The reason why I store pointers in the vector and not the objects
itself, is that these pointers are accepted by other classes/modules
which also may store those pointers and have immediate access to the
interpretation results.
My questions:
* I think the code I have is safe with respect to the "static
initialization order fiasco" because the static vector is within the
class itself. Or am I wrong?
Thanks,
Jeroen
Hi.
If you place your static data inside a class as private data, you
still have no guaranty, that it will be initialized before usage,
because any public method of your class may be called during
initialization of other static stuff. So it is simpler to store such
data either as static data in some function (then it is initialized in
first access of this function) or store statically only pointer to
such data and create it dynamically when used for the first time.
* There does not seem to be a way to delete all class
string_interpreter objects from memory if the program terminates. Is
that bad programming? Or is it normal to depend on the dtor of the
vector to delete all the objects in the list?
You can delete static data in function registered with atexit call.
* Any other bad programming things here?
std::vector<* string_interpreter> is wrong, asterisk has to follow
type, e.g. std::vector<string_interpreter*>