initialization of static reference.

J

John Smith

Hello group.

In the following snipet of code is it guaranteed that foo::coords_
will be initialized before foo::active_coord_ ?

I mean is it guaranteed that the reference &active_coord_ will be
valid ?

Thanks a lot for your response.

//
----------------------------------------------------------------------------------------------------------------------------

#include <vector>
#include <iostream>

class foo {
public:
static std::vector<size_t> coords_;
static size_t &active_coord_;
};

std::vector<size_t> foo::coords_( 1 );

size_t &foo::active_coord_ = coords_[ 0 ]; // Is it safe ?

int main() {
foo ob;

foo::coords_[ 0 ] = 10;
std::cout<<" active coord is "<<ob.active_coord_<<"\n";

return 0;
}
 
Z

Zeppe

Victor said:
Yes, until 'coords_' vector chooses to reallocate its memory.

Unfortunately this leads to very nasty bugs that are not easy to
discover. Of course, if the maximum solution is known, it's always
possible to preallocate with reserve().

Best wishes,

Zeppe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,470
Messages
2,571,807
Members
48,797
Latest member
PeterSimpson
Top