全局變量相互依賴和初始化順序的解決辦法


如果是定義一個全局的map,會出現如下core:

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b449ea in std::_Rb_tree_decrement(std::_Rb_tree_node_base*) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
(gdb) bt
#0  0x00007ffff7b449ea in std::_Rb_tree_decrement(std::_Rb_tree_node_base*) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#1  0x0000000000404071 in std::_Rb_tree_iterator<std::pair<int const, int> >::operator-- (this=0x7fffffffe330) at /usr/include/c++/4.6/bits/stl_tree.h:203
#2  0x00000000004037b2 in std::_Rb_tree<int, std::pair<int const, int>, std::_Select1st<std::pair<int const, int> >, std::less<int>, std::allocator<std::pair<int const, int> > >::_M_insert_unique (this=0x607280, __v=...) at /usr/include/c++/4.6/bits/stl_tree.h:1287
#3  0x000000000040331b in std::map<int, int, std::less<int>, std::allocator<std::pair<int const, int> > >::insert (this=0x607280, __x=...)
    at /usr/include/c++/4.6/bits/stl_map.h:518
#4  0x0000000000402818 in ArgsParser::register_arg (param_name=..., arg_info=0x6080a0) at ./args_parser.cpp:130
#5  0x00000000004017d6 in util::CArgInfo<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::CArgInfo (this=0x6080a0, param_name=...)
    at /data1/mooon/run/include/util/args_parser.h:307
#6  0x00000000004016b3 in util::CStringArgInfo<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::CStringArgInfo (this=0x6080a0, 
    optional=false, param_name=..., default_value=..., help_string=...) at /data1/mooon/run/include/util/args_parser.h:392
#7  0x000000000040143d in __static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535) at x.cpp:7
#8  0x0000000000401523 in _GLOBAL__sub_I__ZN10ArgsParser2ipE () at x.cpp:12
#9  0x0000000000404a8d in __libc_csu_init ()
#10 0x00007ffff7528700 in __libc_start_main (main=0x401374 <main()>, argc=1, ubp_av=0x7fffffffe6a8, init=0x404a30 <__libc_csu_init>, fini=<optimized out>, 
    rtld_fini=<optimized out>, stack_end=0x7fffffffe698) at libc-start.c:185
#11 0x00000000004012b9 in _start ()

問題弄清楚了,是因為全局變量相互依賴的問題,被依賴的晚於初始化造成的(如全局對象A依賴於全局對象B,而B晚於A被構造出來)這和編譯器版本有關,因為之前一直未發現這個問題。解決辦法是,將被依賴的改成局部靜態變量,通過函數方式引用,如:

原來為:static string g_info;
改成:
string& info()
{
    static string s_info; // 局部靜態對象,只有在使用到時才會被構造出來,由於是在全局對象構造中被調用到,所以不存在多線程問題,因為這發生在main函數之前,其它線程還沒有創建出來,如果這個時候就有線程了,那就考慮是否設計合理。
    return s_info;
}

問題就可以解決了。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com