遇到一个问题,例子代码如下:
#include <iostream>
#include <vector>
#include <list>
using namespace std;
class A
{
public:
A(int i) : m_i(i){}
void print(){cout << "A::print m_i = " << m_i <<endl;}
private:
int m_i;
};
int main()
{
std::vector<A> vecA;
for(int i=0; i<10; i++)
{
A a(i);
vecA.push_back(a);
}
std::list<A*> listPointerA;
std::vector<A>::iterator it_begin = vecA.begin();
std::vector<A>::iterator it_end = vecA.end();
while (it_begin != it_end)
{
A *pa = &(*it_begin);
listPointerA.push_back(pa);
pa = listPointerA.back();
pa->print();
it_begin++;
}
cout << "=====================================" <<endl;
//push到list后往vector添一个数据;
for(int i=10; i<11; i++)
{
A a(i);
vecA.push_back(a);
}
std::list<A*>::iterator itbegin = listPointerA.begin();
std::list<A*>::iterator itend = listPointerA.end();
while (itbegin != itend)
{
A *pa = (*itbegin);
pa->print();
itbegin++;
}
return 0;
}
输出:
A::print m_i = 0
A::print m_i = 1
A::print m_i = 2
A::print m_i = 3
A::print m_i = 4
A::print m_i = 5
A::print m_i = 6
A::print m_i = 7
A::print m_i = 8
A::print m_i = 9
=====================================
A::print m_i = 0
A::print m_i = 1
A::print m_i = 2
A::print m_i = 3
A::print m_i = 4
A::print m_i = 5
A::print m_i = 6
A::print m_i = 7
A::print m_i = 8
A::print m_i = 9
请按任意键继续. . .
输出正常,没有问题。但是下面的代码呢,不同在于多添加了10个数据
#include <iostream>
#include <vector>
#include <list>
using namespace std;
class A
{
public:
A(int i) : m_i(i){}
void print(){cout << "A::print m_i = " << m_i <<endl;}
private:
int m_i;
};
int main()
{
std::vector<A> vecA;
for(int i=0; i<10; i++)
{
A a(i);
vecA.push_back(a);
}
std::list<A*> listPointerA;
std::vector<A>::iterator it_begin = vecA.begin();
std::vector<A>::iterator it_end = vecA.end();
while (it_begin != it_end)
{
A *pa = &(*it_begin);
listPointerA.push_back(pa);
pa = listPointerA.back();
pa->print();
it_begin++;
}
cout << "=====================================" <<endl;
//push到list后往vector添10个数据;
//不同在于添加了10个数据
for(int i=10; i<21; i++)
{
A a(i);
vecA.push_back(a);
}
std::list<A*>::iterator itbegin = listPointerA.begin();
std::list<A*>::iterator itend = listPointerA.end();
while (itbegin != itend)
{
A *pa = (*itbegin);
pa->print();
itbegin++;
}
return 0;
}
输出:
A::print m_i = 0
A::print m_i = 1
A::print m_i = 2
A::print m_i = 3
A::print m_i = 4
A::print m_i = 5
A::print m_i = 6
A::print m_i = 7
A::print m_i = 8
A::print m_i = 9
=====================================
A::print m_i = -572662307
A::print m_i = -572662307
A::print m_i = -572662307
A::print m_i = -572662307
A::print m_i = -572662307
A::print m_i = -572662307
A::print m_i = -572662307
A::print m_i = -572662307
A::print m_i = -572662307
A::print m_i = -572662307
请按任意键继续. . .
原因在于std的内存分配管理。