[英]Aliasing between C++ struct and std:vector element--why?
在C ++中, csi
是具有整數字段的結構:
struct CentScanInfo
{
int runId;
...
};
以下代碼處理csi
結構的向量:
// 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
...
}
我不希望更改變量csi
會影響向量csiv
任何元素。 為什么會發生這種情況,以及應該如何更改代碼以使其不發生?
Visual Studio 2017 15.4.5; 64位Windows 7 Pro
別名是通過pFI
指針進行的。 在填充了向量的第一個循環中,每個csi
都有一個唯一的pFI
。 因此,在排序之后使用csi
時, csi.pFI
與向量的最終元素相同(排序之前)。
解決方法是在更改runId
之前添加另一個FI
對象並設置其pFI
字段:
CFileInfo sentinel; csi.pFI = &sentinel;
這本來應該很明顯,但事實並非如此!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.