|
-
July 28th, 2004, 05:56 AM
#1
How to initialise a static stl vector?
I have a class containing a static vector. I would be grateful if someone could tell me how to initialise this vector so that when this class is instantiated, the vector contains some meaningful data the first time round. NB There is only ever one instance of the class at a time, and the vector being static will hold the data that was set last time the class was instantiated.
eg in classA.h, where MaterialsClass is just a data class/structure
classA {
...
static vector<MaterialsClass> m_Vec;
};
in classA.cpp
vector<MaterialsClass> classA::m_Vec; // compiler is happy with this
classA::m_Vec.clear(); // COMPILE ERROR - syntax error ';' expected before '.'
// I want to create some MaterialsClass objects and do
// m_Vec.push_back(...)
classA::classA()
{
}
other classA functions etc
-
July 28th, 2004, 06:00 AM
#2
The vector will automatically be empty when it is first created.
If you subsequently want to empty it, you can simply call clear() at that moment.
If you want your vector to be initialised with some data in it, then wrap it in another class and make a static instance of that class instead. This could be your typical "singleton".
Beware of thread-safety issues when using a static class member.
-
July 28th, 2004, 06:04 AM
#3
Well
1. You could initialize it by first initializing a plain C-style array and then using this
to initialize the vector with a constructor.
2. Use some stratup code
Code:
vector<MaterialsClass> classA::m_Vec;
namespace
{
bool InitMaterialsVector()
{
ClassA::m_Vec.push_back(MaterialsClass(...));
...
}
bool MaterialsVectorIsInit = InitMaterialsVector();
}
Wakeup in the morning and kick the day in the teeth!! Or something like that.
"i don't want to write leak free code or most efficient code, like others traditional (so called expert) coders do."
-
July 28th, 2004, 06:27 AM
#4
Thanks very much. I'll take your advice and wrap the vector in another class.
Since I'm only ever working with one instance of the class, am I right in assuming I don't need to worry about thread safety? Or might there be more to it than that?
Thanks again
-
July 28th, 2004, 08:56 AM
#5
 Originally Posted by JonnoA
Since I'm only ever working with one instance of the class, am I right in assuming I don't need to worry about thread safety? Or might there be more to it than that?
Well...this rather depends on how many threads actually accessing the one class instance at the same time...if there are more than one thread accessing the class (and the 'vector'), then you would need to synchronize the access...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|