繁体   English   中英

具有标准容器和常量引用的c ++代码显示意外的内存

[英]c++ code with standard containers and constants references exhibits unexpected memory

我们在生产中使用下面的代码(大致相同),并且看到一些奇怪的行为。 标有“ HERE”的部分始终输出最后插入accrualRows词典的内容。 如果我们更改hash_map以存储指向“行”的指针,则一切正常。 我在std容器中使用const&有点怀疑。您不能在标准容器中使用引用,但是这些是常量引用,我知道在某些地方这些引用是不同的(例如:您可以分配临时变量和常量引用的文字)

#define hash_map std::tr1::unordered_map
//build up a hash map between deal index and the row for ones we care about

    typedef hash_map<int, const Row &> RowMap;
    RowMap accrualRows;    
    for( int i = 0; i < listItems.numResults(); ++i )
    {
        const Row & accrual = listItems.getResult(i);
        if( accrual.someVar )
        {
            accrualRows.insert( std::make_pair( accrual.index, accrual ) );
         }
    }

    //go through every row and if deal index is in our accrualRows, then
    //modify 

    for( int i = 0; i < numResults(); ++i )
    {
        ExposureRow & exposure = getResult(i);
        RowMap::const_iterator it = accrualRows.find( exposure.index );

        if( it != accrualRows.end() )
        {
            // HERE
            cout << it->second.someVar << endl;
        }
    }
}

谁能看到问题所在?

您不能将引用存储在容器中。 容器只能存储对象 如果需要存储“引用”,则可以使用std::reference_wrapper或使用指针。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM