-3

こんにちは、以下のコードを実行すると、このエラーが表示されます。「セグメンテーション エラー (コア ダンプ)」理由がわかりません\ 誰か助けてください。ありがとう

#ifndef __LIB_TAG_STRINGS_H__
#define __LIB_TAG_STRINGS_H__

//============
//stl
#include <deps.h>
#include <string>
namespace tags
 {
   const std::string tag1 ("TAG_1");
   const std::string tag2 ("TAG_2");
 }//END namespace TAGS

namespace attributes
 {
  const std::string attribute1 ("ATTRIBUTE_1");
  const std::string attribute2("ATTRIBUTE_2");
 }

class _Name 
 {
  public:

  _Name ()
   {
    /**This constructor is used to map some tags with the strings**/
    string_map.insert (std::make_pair (std::string ("TAGNOTE1"), tags::tag1 ));
    string_map.insert (std::make_pair (std::string ("TAGNOTE2"), tags::tag2 ));
   };

 const std::string& getName (const std::string& class_name) const
   {   
    std::map<std::string, std::string>::const_iterator i = string_map.find(class_name);
    return (i != string_map.end ()) ? i->second : null_string;
  }


   private:
    std::map<std::string, std::string> string_map;
    std::string null_string;
 };

namespace Name
 {
  const _Name NAME;
 }
#endif

コアは実行時にダンプされました。これは、GDB がエラーを指摘しているコードです。

GDB ログ:

プログラム受信信号 SIGSEGV、セグメンテーション違反。
0x0000003b00e9d23b in std::basic_string, std::allocator >::basic_string(std::basic_string, std::allocator > const&) () from /usr/lib64/libstdc++.so.6
個別の debuginfo がありません。次を使用してください: x86_64 nss-softokn-freebl-3.12.9-11.el6.x86_64 openssl-1.0.0-20.el6_2.5.x86_64 zlib-1.2.3-27.el6.x86_64
(gdb) ここで
0 0x000strong text0003b00e9d23b in std::basic_string, std::allocator >::basic_string(std::basic_string, std::allocator > const&) () from /usr/lib64/libstdc++.so.6
1 0x00007ffff1375372 in _Name::_Name (this=0x7ffff15a9b60)
    /prog/lib/tag_strings.h:229 で
2 0x00007ffff139581b in __static_initialization_and_destruction_0 ()
    /prog/lib/tag_strings.h:257 で
dest.cxx:679 の dest.cxx(void) () をキーとする 3 つのグローバル コンストラクター
4 0x00007ffff1398516 in __do_global_ctors_aux () from ./dest.so
5 0x00007ffff135a2bb in _init () from ./dest.so
6 0x00007fffe361f000 in ?? ()
7 0x0000003af860e535 in _dl_init_internal () from /lib64/ld-linux-x86-64.so.2
/lib64/ld-linux-x86-64.so.2 からの _dl_start_user () の 8 0x0000003af8600b3a
9 0x0000000000000001 in ?? ()
10 0x00007fffffffe128 in ?? ().
11 0x0000000000000000 in ?? ().
4

1 に答える 1

2

静的な初期化順序の問題のように見えます。

NAME オブジェクトが構築されると、tag1/tag2 オブジェクトにアクセスしますが、これらがまだ構築されているという保証はありません!

関数に依存するオブジェクトを変更してみてください。

namespace tags {
    static std::string tag1() { return std::string("TAG1"); }
    ...
}

...
string_map.insert (std::make_pair (std::string ("TAGNOTE1"), tags::tag1() ));
...
于 2013-05-24T10:57:02.387 に答える