参考: C++ Primer Plus (第六版)----16章
一.string 类(略)
二. 智能指针
使用智能指针包括三种:auto_ptr、unique_ptr、shared_ptr
智能指针模板都定义了类似指针的对象,可以将new获得的地址赋值给这种对象,当指针过期时,其析构函数将使用delete来释放内存;相比与普通指针,无需再在程序中利用delete释放。
构造函数:
template<class X>
class auto_ptr
{
explicit auto_ptr(X* p = 0) throw();
...
}
要创建智能指针模板,必须包含头文件 memory,然后使用通常的模板语法来实例化所需类型的指针,如下所示:
auto_ptr<double> pd(new double);
auto_ptr<string> ps(new string);
unique_ptr<double> pdu(new double);
shared_ptr<string> pss(new string);
std::string * ps = new std::string; //普通指针 创建对象
std::auto_ptr<std::string> ps(new std::string); //智能指针 创建对象
示例:
// smrtptrs.cpp -- using three kinds of smart pointers
#include <iostream>
#include <string>
#include <memory>
class Report
{
private:
std::string str;
public:
Report(const std::string s) : str(s) { std::cout << "Object created!\n"; }
~Report() { std::cout << "Object deleted!\n"; }
void comment() const { std::cout << str << "\n"; }
};
int main()
{
{
std::auto_ptr<Report> ps (new Report("using auto_ptr"));
ps->comment(); // use -> to invoke a member function
}
{
std::shared_ptr<Report> ps (new Report("using shared_ptr"));
ps->comment();
}
{
std::unique_ptr<Report> ps (new Report("using unique_ptr"));
ps->comment();
}
// std::cin.get();
return 0;
}
可以看到,智能指针使用方法与普通指针类似。
选择智能指针:
1. 如果程序要使用多个指向同一个对象的指针,应选择 shared_ptr
2. 如果程序不需要使用多个指向同一个对象的指针,可选择 unique_ptr
三.标准模板库
标准模板库包括:容器、迭代器、函数对象和算法的模板。
1.模板类vector
在头文件 vector 中定义了一个vector模板,要创建模板对象,可使用通常的<type>表示法来指出要使用的类型;
vector 使用动态内存分配,因此可以用初始化参数来指出需要多少矢量;
#include vector
using namespace std;
vector<int> ratings(5); // a vector of 5 ints
int n;
cin >> n;
vector<double> scores(n) // a vector of n doubles
由于运算符 [ ] 被重载,因此创建vector对象后,可以使用通常的数组表示法来访问各个元素:
ratings[0] = 9;
for (int i = 0; i < n; i++)
cout << scores[i] << endl;
2.可对矢量执行的操作
具体操作方法见书本:
size():返回容器元素数目;
swap():交换两个容器的内容;
begin():返回一个指向容器第一个元素的迭代器(指针);
end():返回一个超过容器尾的迭代器(指针);
push_back():将元素添加到矢量末尾;
erase():删除矢量中给定区间的元素;
insert():插入矢量中给定区间的元素;
...