c++ - 将局部 vector 复制到 map 中某个键的值时遇到段错误

标签 c++ vector stl segmentation-fault

class TrackSymbol
{
        protected: static std::map<int, std::vector<char> > _trackTypeToIdentificationCodeMap ;

        protected: static char _identificationCodeChars[][2] ;
} ;

在实现文件中:

std::map<int, std::vector<char> > TrackSymbol::_trackTypeToIdentificationCodeMap ;

char TrackSymbol::_identificationCodeChars[][2] =
{
    { ' ', ' ' },
    { 'S', '6' },
    { 'Z', 'U' }
} ;

在构造函数中,我试图用 _identificationCodeChars 中的适当值填充局部 vector ,但在拷贝中遇到段错误:

    for ( int i = 0 ; i < sizeof( _identificationCodeChars ) / sizeof( _identificationCodeChars[0] ) ; i++ )
    {
        std::vector<char> vec ;
        vec.push_back( _identificationCodeChars[i][0] ) ;
        vec.push_back( _identificationCodeChars[i][1] ) ;

        _trackTypeToIdentificationCodeMap[i] = vec ; //Segfault here
    }

据我所知,赋值运算符将对本地 vector 进行硬拷贝,所以我对它为什么会出现段错误感到有点困惑。另外,在我当前的环境中,我只能使用 C98,所以我无法使用扩展初始化列表等东西。

最佳答案

静态成员变量基本上是一个奇特的全局变量。特别是该 map 的构造函数在该程序的执行中仅被调用一次,而不是为每个 TrackSymbol 对象调用一次。 (但是,它保证在执行 int main() 的第一行之前运行。)

很难从您所说的内容中判断出来,但我的猜测是您在 _trackTypeToIdentificationCodeMap 的构造函数运行之前实例化了一个 TrackSymbol 对象,例如在之前定义的全局变量中_trackTypeToIdentificationCodeMap 或在另一个文件中。直接的解决方法是移动该定义。更好的解决方法可能是使该成员变量成为非静态的(如果您能承受性能损失)或使用单例函数(在旧的 C++ 版本中,这不能保证是线程安全的):

std::map<int, std::vector<char> > getCodeMap_internal()
{
    static char _identificationCodeChars[][2] =
    {
        { ' ', ' ' },
        { 'S', '6' },
        { 'Z', 'U' }
    } ;
    std::map<int, std::vector<char> > _trackTypeToIdentificationCodeMap;
    for ( int i = 0 ; i < sizeof( _identificationCodeChars ) / sizeof( _identificationCodeChars[0] ) ; i++ )
    {
        std::vector<char> vec ;
        vec.push_back( _identificationCodeChars[i][0] ) ;
        vec.push_back( _identificationCodeChars[i][1] ) ;

        _trackTypeToIdentificationCodeMap[i] = vec ;
    }
    return _trackTypeToIdentificationCodeMap;
}

const std::map<int, std::vector<char> >& getCodeMap()
{
    static std::map<int, std::vector<char> > _trackTypeToIdentificationCodeMap
        = getCodeMap_internal();
    return _trackTypeToIdentificationCodeMap;
}

关于c++ - 将局部 vector 复制到 map 中某个键的值时遇到段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45443048/

相关文章:

c++ - Boost 或 STL 是否提供类似于 QString 的功能?

string - 在 Vec<i8> 和 &str 之间转换

c++ - 获取返回的 multimap 迭代器的内容

C++ 显示具有 vector 的 map

c++ - constexpr 计算量的实际限制

c++ - 来自聚合类的对象 vector 中的 Push_back

c++ - 模板声明不能出现在 block 范围内

c++ - 获取按 map 值排序的 map 键 vector 的最快方法?

c++ - 从同一进程中的 C++ 程序运行可执行文件

c++ - 使用 C++ 和 openCV 进行立方体检测