简体   繁体   中英

Aliasing between C++ struct and std:vector element--why?

In C++, csi is a structure with integer fields:

struct CentScanInfo
{
    int runId;
...
};

The following code processes a vector of csi structures:

// Create vector of csi structures
CentScanInfo csi; std::vector<CentScanInfo> csiv;
for(j = 0; j < n; j++)
{
    // ... code to store values into a csi structure
    csiv.push_back(csi);
}

// Sort the vector, then process entries
if(csiv.size() > 0)
{
    sort(csiv.begin(), csiv.end(), CsiSortCriterion);
    // BEFORE: csiv[n-2] = 3605406551, which is correct
    csi.pFI->runId = -99;
    // AFTER: csiv[n-2] = -99, which is wrong
    ...
}

I do not expect changing the variable csi to affect any element of the vector csiv . Why does this happen, and how should the code be changed so it does not occur?

Visual Studio 2017 15.4.5; 64-bit Windows 7 Pro

The aliasing is taking place via the pFI pointer. In the first loop, where the vector is populated, each csi has a unique pFI . Thus, when csi is used following the sort, csi.pFI is the same as the final element of the vector (before sorting).

The fix is to add another FI object, and set its pFI field, before changing runId :

CFileInfo sentinel; csi.pFI = &sentinel;

This should have been obvious, but obviously it wasn't!

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