简体   繁体   English

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

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

We have the code below (roughly the same) in production, and am seeing some weird behaviour. 我们在生产中使用下面的代码(大致相同),并且看到一些奇怪的行为。 The section marked 'HERE' always outputs whatever was last inserted into the accrualRows dictionary. 标有“ HERE”的部分始终输出最后插入accrualRows词典的内容。 If we change the hash_map to store pointers to 'Row', then everything works fine. 如果我们更改hash_map以存储指向“行”的指针,则一切正常。 I'm a bit suspicious of using a const & in the std containers.. you can't use references in standard containers, but these are constant references, which I know in some places are treated different (eg: you can assign temporary variables and literals to constant references) 我在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;
        }
    }
}

Can anyone see what the problem is? 谁能看到问题所在?

You cannot store references in a container. 您不能将引用存储在容器中。 A container can only store objects . 容器只能存储对象 If you need to store a "reference," you can either use std::reference_wrapper or use a pointer. 如果需要存储“引用”,则可以使用std::reference_wrapper或使用指针。

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

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