我知道这是有问题的,但我很好奇这样做是否会导致未定义的行为?
class A
{
public:
int i;
};
class As {
public:
bool operator()(const A* l, const A* r)
{
return l->i < r->i;
}
};
int main() {
std::set<A*,As> s;
A* a1 = new A();
a1->i = 9;
A* a2 = new A();
a2->i = 2;
s.insert(a1);
s.insert(a2);
for(std::set<A*,As>::iterator i = s.begin(); i != s.end(); ++i)
std::cout<<(*i)->i<<std::endl;
for(std::set<A*,As>::iterator i = s.begin(); i != s.end(); ++i)
{
if((*i)->i == 2)
(*i)->i = 22;
}
for(std::set<A*,As>::iterator i = s.begin(); i != s.end(); ++i)
std::cout<<(*i)->i<<std::endl;
//now s is in incorrect state, insert all elements into a tmp one
std::set<A*,As> t;
for(std::set<A*,As>::iterator i = s.begin(); i != s.end(); ++i)
t.insert(*i);
s.swap(t);
for(std::set<A*,As>::iterator i = s.begin(); i != s.end(); ++i)
std::cout<<(*i)->i<<std::endl;
}
输出是:
2
9
22
9
9
22
由 GCC 4.7 编译时似乎工作正常,但我不知道这是否只是运气。