Re: Initialize static members outside the class
On Jul 19, 6:52 pm, Steven Woody <narkewo...@gmail.com> wrote:
On Jul 17, 4:39 pm, James Kanze <james.ka...@gmail.com> wrote:
On Jul 17, 4:16 am, Steven Woody <narkewo...@gmail.com> wrote:
On Jul 16, 4:46 pm, James Kanze <james.ka...@gmail.com> wrote:
[...]
This seems interesting! I will try right now. And, in my real
program, the elements contained in the std::vector are actually
std::pair objects.
std::pair of what?
If possible, I would urge you to consider replacing std::pair
with a POD struct, and using either tr1::array or a C style
array with static initializers. That ensures that you will
never encounter an order of initialization problem, and will
work just as well as std::vector. (Most of the time I've used
the solution I just explained has been with std::map. And
looking something up in an std::map can be significantly faster
than using a linear search over an array. Although... unless
the number of elements is large, the difference often isn't
important.)
Ok, I understand. Defining a POD structure instead of using a
std::pair should work. But the point is, also without
std::vector, is it?
It depends. In general, I don't like std::pair, because I've
never had a pair in which the elements should have names like
first and second. If the element is being used to construct an
std::vector in the same translation unit, of course, the order
of initialization issues don't apply; the vector will have
dynamic initialization, regardless. So it's really just a
question of whether you write:
std::pair< int, int > const initVector[] =
{
std::pair< int, int >( 1, 2 ) ;
std::pair< int, int >( 3, 4 ) ;
// ...
} ;
or
MyStruct const initVector[] =
{
{ 1, 2 },
{ 3, 4 },
} ;
And whether you want the constructor elsewhere. (There's also
nothing wrong with defining MyStruct:
struct MyStruct
{
int first ;
int second ;
operator std::pair< int, int >() const
{
return std::pair< int, int >( first, second ) ;
}
} ;
to allow writing the initialization vector as above, but to have
std::pair in the vector.
By the way, my std::pair is <int, int>, as simple as you guessed :-)
In which case, *IF* it is static and const, and there aren't
other overriding issues, why not use boost::array or a C style
array. (Note that I wouldn't recommend this to a pure beginner.
Using std::vector should be the automatic first reaction. But
you seem to have already reached that point, so you can start
considering the few exceptions.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34