我正在處理的代碼中,更多可變長度對象中的1個作爲所有單位的向量存儲,即假設每個字母都是一個單位,並且同一個字母是同一個高級對象。 載體可以含有類似如下:aaaabbcccdeeffff ...std vector const_iterator賦值訪問衝突
該載體是具有操作符[]中定義這樣一類的內部專用變量,對於在上述
- obj[0] returns an const_iterator to the first "a"
- obj[1] to the first "b"
- obj[2] to the first "c" etc.
const AI::GeneArray::const_iterator& AI::Chromosome::operator[](int index) const {
GeneArray::const_iterator pGene;
int cIndex;
for (cIndex=0,pGene = this->vGenes.cbegin();pGene != this->vGenes.cend();pGene++, cIndex++) {
if (index == cIndex) { break; }
(*pGene)->EndOfBlock(pGene); }
return pGene; }
矢量然後我有以下另一個功能
AI::GeneArray::const_iterator function = vChromosome[0];
這會導致訪問衝突錯誤。
調用堆棧的上面我的功能如下
AI.exe!std::_Vector_const_iterator<std::_Vector_val<AI::Gene *,std::allocator<AI::Gene *> > >::_Vector_const_iterator<std::_Vector_val<AI::Gene *,std::allocator<AI::Gene *> > >(const std::_Vector_const_iterator<std::_Vector_val<AI::Gene *,std::allocator<AI::Gene *> > > & __that) + 0x2f byte
AI.exe!std::_Iterator012<std::random_access_iterator_tag,AI::Gene *,int,AI::Gene * const *,AI::Gene * const &,std::_Iterator_base12>::_Iterator012<std::random_access_iterator_tag,AI::Gene *,int,AI::Gene * const *,AI::Gene * const &,std::_Iterator_base12>(const std::_Iterator012<std::random_access_iterator_tag,AI::Gene *,int,AI::Gene * const *,AI::Gene * const &,std::_Iterator_base12> & __that) + 0x2f bytes
AI.exe!std::_Iterator_base12::_Iterator_base12(const std::_Iterator_base12 & _Right) Line 118
AI.exe!std::_Iterator_base12::operator=(const std::_Iterator_base12 & _Right) Line 123 + 0x5 bytes
最後的呼叫是
_Iterator_base12& operator=(const _Iterator_base12& _Right)
{ // assign an iterator
if (_Myproxy != _Right._Myproxy)
_Adopt(_Right._Myproxy->_Mycont);<- This line
return (*this);
}
根據我的調試器(的Visual C++ 2010速成)
_Right._Myproxy->
_Mycont = CXX0030: Error: expression cannot be evaluated
_Myfirstiter = CXX0030: Error: expression cannot be evaluated
否則在我的項目中,我有類似的代碼使用std :: list,而不是正確工作的向量
parents = new ChromosomeList::const_iterator[C];
*(parents) = --(this->vChromosomes.cend());
for (int i=1;i<C;i++) {
*(parents+i) = ChromosomeList::const_iterator((*(parents+i-1)));
(*(parents+i))--; }
我檢查了[0]
這個值是正確的類型,
const AI::GeneArray::const_iterator &
我谷歌搜索類似問題的
vChromosome返回的值,我所能找到的所有問題都與使用迭代器循環遍歷矢量相關的問題。
即
for (AI::GeneArray::const_iterator pGene = Genes.cbegin();pGene != Genes.cend();pGene++)
這樣的代碼在我的項目中工作正常。
v染色體,不是一個向量,它是一個包含構成大對象的子對象(基因)的向量的類,當放置在一個序列中時,子對象在危害之前接下來會發生什麼,這會創建塊, 我已經爲這個類定義了一個[]運算符,使得它返回並且cont_iterator被存儲在我的基因向量中的第n個較大對象的第一個基因。 該矢量是有效的,也是由vChromosome [0]返回的迭代器,我用我的調試器來查看這些值。 – glenflet
@glenflet:如果迭代器是有效的,做它的分配不會使任何事情失效或導致訪問衝突。聽起來像你在未向我們展示的代碼中存在未定義的行爲(如在其他類的'operator []'中)。 –
問題解決了,我在運算符[]函數中返回一個局部變量。 – glenflet