开始复习一些比较基础的知识,发现自己很多基础点都有遗忘,因此写一下记录一下。
这次开始复习双向链表std::List,我们先上一段代码:
class MyClass {
public:
MyClass(int val) : val_(val) {//构造函数
std::cout << "Construct() " << this << " " << val_ << std::endl;
}
MyClass(const MyClass &my_class) {//拷贝构造函数
val_ = my_class.val_;
std::cout << "Copy() " << this << std::endl;
}
~MyClass() {//析构函数
std::cout << "Destruct() " << this << " " << val_ << std::endl;
}
void OutputVal() {//输出val
std::cout << "OutputVal " << this << " " << val_ << std::endl;
}
int val_;
};
int main() {
std::list<MyClass> myclass_list;
{
myclass_list.push_back(MyClass(1));//使用push_back塞入
myclass_list.push_back(MyClass(2));//使用push_back塞入
myclass_list.push_back(MyClass(3));//使用push_back塞入
for (auto it = myclass_list.begin(); it != myclass_list.end(); it++) {
it->OutputVal();//遍历一遍list
}
for (auto it = myclass_list.begin(); it != myclass_list.end(); it++) {
if (it->val_ == 2) {//删除列表中值为2的项
myclass_list.erase(it);
break;//此处需要break,如果继续下去,此时由于已经erase了2这个值,因此迭代器已经失效,如果再继续,会导致崩溃。
}
}
}
for (auto it = myclass_list.begin(); it != myclass_list.end(); it++) {
it->OutputVal();//遍历一遍list
}
return 0;
}
接下来将一条条地讲解这边输出的结果:
Construct() 012FFEE8 1 //1的构造函数,在MyClass(1)中输出
Copy() 014951C0 //使用push_back塞入,传入前先通过拷贝函数构造了一份新的,并将新的插入到list中
Destruct() 012FFEE8 1 //MyClass(1)作用域结束,因此调用析构
Construct() 012FFEE8 2 //同1
Copy() 01494458 //同1
Destruct() 012FFEE8 2 //同1
Construct() 012FFEE8 3 //同1
Copy() 01495298 //同1
Destruct() 012FFEE8 3 //同1
OutputVal 014951C0 1 //输出list中的1对应的地址,与拷贝构造函数生成的地址一致。
OutputVal 01494458 2 //输出list中的2对应的地址,与拷贝构造函数生成的地址一致。
OutputVal 01495298 3 //输出list中的3对应的地址,与拷贝构造函数生成的地址一致。
Destruct() 01494458 2 //调用了erase函数,将list中的2销毁,因此触发了2的析构
OutputVal 014951C0 1 //仍在列表中
OutputVal 01495298 3 //仍在列表中