简体   繁体   中英

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. If we change the hash_map to store pointers to 'Row', then everything works fine. 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)

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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