stl::vector erase 时元素析构问题的辟谣

网上传言,标准库中的vector在调用erase函数删除元素时,存在元素析构问题。其实是那篇文章的例子有问题(文章地址就不贴了,想看去google搜),vector的erase函数是完全没问题的,大家可以放心用。看下面源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>  
#include <string>
#include <vector>

using namespace std;

struct role{
string name;
char *p;
role(const char* n)
: name(n)
{
p = new char;
cout << name << " new" << endl;
}
role(const role &r)
: name(r.name)
{
p = new char;
cout << name << " copy" << endl;
}
const role & operator =(const role &r) {
if (this == &r) {
return *this;
}
cout << name << " delete before assign" << endl;
name = r.name;
cout << "copy assign from " << name << endl;
return *this;
}
~role() { cout << name << " delete" << endl; }
};

void test(){
role r1("小李"), r2("小强"), r3("小狗"), r4("小明");

typedef vector<role> RoleVec;
RoleVec rvec;
rvec.reserve(10);

cout << "----------分界线1----------" << endl;
rvec.push_back(r1);
rvec.push_back(r2);
rvec.push_back(r3);
rvec.push_back(r4);
cout << "----------分界线2----------" << endl;
RoleVec::iterator iter = rvec.begin();
RoleVec::iterator iend = rvec.end();

{
cout << "----------分界线3----------" << endl;
for(;iter != iend;++iter) {
if((*iter).name.compare("小强") == 0) {
rvec.erase(iter);
break;
}
}
cout << "----------分界线4----------" << endl;
}
rvec.clear();
cout << "----------分界线5----------" << endl;
}

int main() {
test();
return 0;
}

结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
*@****:~/5$ ./a.out  
小李 new
小强 new
小狗 new
小明 new
----------分界线1----------
小李 copy
小强 copy
小狗 copy
小明 copy
----------分界线2----------
----------分界线3----------
小强 delete before assign
copy assign from 小狗
小狗 delete before assign
copy assign from 小明
小明 delete
----------分界线4----------
小李 delete
小狗 delete
小明 delete
----------分界线5----------
小明 delete
小狗 delete
小强 delete
小李 delete

文章目录