动态内存
- 全局对象在程序启动时分配,结束时销毁。局部对象在进入程序块时创建,离开块时销毁。局部static对象在第一次使用前分配,在程序结束时销毁。动态分配对象:只能显式地被释放。
- 静态内存用来保存局部static对象、类static对象、定义在任何函数之外的变量。栈内存用来保存定义在函数内的非static对象。堆内存,又称自由空间,用来存储动态分配的对象。
- 动态内存管理:
new:在动态内存中为对象分配空间并返回一个指向该对象的指针。
delete:接受一个动态对象的指针,销毁该对象,并释放与之关联的内存。
动态内存和智能指针
- shared_ptr允许多个指针指向同一个对象。unique_ptr则独占所指向的对象。weak_ptr是一个伴随类,是一种弱引用,指向shared_ptr所管理的对象。头文件memory。
shared_ptr类
shared_ptr<string> p1;
shared_ptr<list<int>> p2;
if(p1 && p1->empty())
*p1 = "hi";
- shared_ptr和unique_ptr都支持的操作
shared_ptr<T> sp
unique_ptr<T> up
p
*p
p->mem
p.get()
swap(p, q) p.swap(q)
make_shared<T>(args)
shared_ptr<T>p(q)
p = q
p.unique()
p.use_count()
- make_shared函数(最安全的分配和使用动态内存的方法)
shared_ptr<int> p3 = make_shared<int>(42);
shared_ptr<string> p4 = make_shared<string>(10,'9');
shared_ptr<int> p5 = make_shared<int>();
auto p6 = make_shared<vector<string>>();
auto p = make_shared<int>(42);
auto q(p);
- 每个shared_ptr都有一个关联的计数器,通常称其为引用计数。拷贝一个shared_ptr,计数器都会递增,如用一个shared_ptr初始化另一个,或将它作为参数传递给一个函数,以及作为函数的返回值,它所关联的计数器就会递增。当给shared_ptr赋予一个新值或是shared_ptr被销毁,如一个局部的shared_ptr离开其作用域时,计数器会递减。一旦一个shared_ptr的计数器变为0,它就会自动释放自己所管理的对象。
auto r = make_shared<int>(42);
r = q;
- shared_ptr自动销毁所管理的对象:当指向一个对象的最后一个shared_ptr被销毁时,shared_ptr类会自动销毁此对象。通过析构函数实现。shared_ptr的析构函数会递减它随指向的对象的引用计数。如果引用计数变为0,shared_ptr的析构函数就会销毁对象,并释放它占用的内存。
- shared_ptr还会自动释放相关联的内存:
shared_ptr<Foo> factory(T arg){
return make_shared<Foo>(arg);
}
void use_factory(T arg){
shared_ptr<Foo> p = factory(arg);
}
shared_ptr<Foo> use_factory(T arg){
shared_ptr<Foo> p = factory(arg);
return p;
}
- shared_ptr在无用之后仍然保留的一种可能情况是,你将shared_ptr存放在一个容器中,随后重排了容器,从而不再需要某些元素。这种情况下,你应该确保用erase删除那些不再需要的shared_ptr元素。
- 使用了动态生存期的资源的类
- 程序不知道自己需要使用多少对象
- 程序不知道所需对象的准确类型
- 程序需要在多个对象间共享数据
- 动态内存是为了让多个对象能共享相同的底层数据。目前为止,我们使用过的类中,分配的资源都与对应对象生存期一致。例如,每个vector拥有其自己的元素。当我们拷贝一个vector时,原vector和副本vector中的元素是相互分离的。
vector<string> v1;
{
vector<string> v2 = {};
v1 = v2;
}
Blob<string> b1;
{
Blob<string> b2 = {};
b1 = b2;
}
定义StrBlob类
- 为了保证vector中的元素继续存在,我们将vector保存在动态内存中。
- 构造函数的initializer类型参数,可以接受一个初始化器的花括号列表。
class StrBlob{
public:
typedef std::vector<std::string>::size_type size_type;
StrBlob();
StrBlob(std::initializer_list<std::string> il);
size_type size() const {return data->size();}
bool empty() const {return data->empty();}
void push_back(const std::string& t){data->push_back(t);}
void pop_back();
std::string& front();
std::string& back();
private:
std::shared_ptr<std::vector<std::string>> data;
void check(size_type i,const std::string& msg) const;
};
StrBlob::StrBlob():data(make_shared<vector<string>>()){}
StrBlob::StrBlob(initializer_list<string> il):data(make_shared<vector<string>>(il)){}
- pop_back,front,back操作访问vector中的元素。这些操作在试图访问元素之前必须检查元素是否存在。定义了一个名为check的private工具函数,它检查一个给定索引是否在合法范围内。
void StrBlob::check(size_type i,const string& msg) const{
if(i >= data->size())
throw out_of_range(msg);
}
string& StrBlob::front(){
check(0,"front on empty StrBlob");
return data->front();
}
string& StrBlob::back(){
check(0,"back on empty StrBlob");
return data->back();
}
void StrBlob::pop_back(){
check(0,"pop_back on empty StrBlob");
data->pop_back();
}
- StrBlob的拷贝,赋值和销毁:当我们拷贝赋值或销毁一个StrBlob对象时,它的shared_ptr成员会被拷贝,赋值或销毁。拷贝一个shared_ptr会递增其引用计数,将一个shared_ptr赋予另一个shared_ptr会递增赋值号右侧shared_ptr的引用计数,递减左侧shared_ptr的引用计数。引用计数为0,所指向的对象会被自动销毁。对于由StrBlob构造函数分配的vector,当最后一个指向它的StrBlob对象被销毁时,它会随之被自动销毁。
直接管理内存
- new分配内存,delete释放new分配的内存。容易出错。自己直接管理内存的类不能依赖类对象拷贝,赋值和销毁操作的任何默认定义。智能指针的程序更容易编写和调试。
使用new动态分配和初始化对象
- 在自由空间分配的内存是无名的,因此new无法为其分配的对象命名,而是返回一个指向该对象的指针。
int* pi = new int;
string* ps = new string;
int* pi = new int;
int *pi = new int(1024);
string *ps = new string(10,'9');
vector<int> *pv = new vector<int>{0,1,2,3,4,5,6,7,8,9};
string *ps1 = new string;
string *ps = new string();
int *pi1 = new int;
int *pi2 = new int();
auto p1 = new auto(obj);
auto p2 = new auto{a,b,c};
动态分配的const对象
const int *pci = new const int(1024);
const string *pcs = new const string;
内存耗尽
int *p1 = new int;
int *p2 = new (nothrow) int;
释放动态内存
delete p;
Foo* factory(T arg){
return new Foo(arg);
}
void use_factory(T arg){
Foo *p = factory(arg);
}
void use_factory(T arg){
Foo *p = factory(arg);
delete p;
}
Foo* use_factory(T arg){
Foo *p = factory(arg);
return p;
}
- 常见问题:忘记delete内存,使用已经释放掉的对象,同一块内存释放两次。
delete之后重置指针值
- 空悬指针:delete之后指针变得无效,但在很多机器上指针仍然保存着动态内存的地址。delete之后,就成了指向一块曾经保存数据对象但现在已经无效的内存的指针。
- 避免空悬指针的方法:在指针离开其作用域前释放它所关联的内存。或者在delete之后将nullptr赋予指针。
- 动态内存基本问题是可能有多个指针指向相同的内存,在delete内存之后重置指针的方法只对这个指针有效,对其他仍指向已释放的内存的指针是没有作用的。
int *p(new int(42));
auto q = p;
delete p; //p和q均变为无效
p = nullptr;//重置p对q没有任何作用
//实际中,查找指向相同内存的所有指针是异常困难的。
shared_ptr和new结合使用
shared_ptr<double> p1;
shared_ptr<int> p2(new int(42));
//接受指针参数的智能指针构造函数是explicit,因此不能将一个内置指针隐式转换为一个智能指针必须使用直接初始化形式。
shared_ptr<int> p1 = new int(42);//wrong
shared_ptr<int> p2(new int(42));
//返回shared_ptr的函数也不能在其返回语句中隐式转换一个普通指针
shared_ptr<int> clone(int p){
return new int(p);//wrong
return shared_ptr<int>(new int(p));
}
//定义和改变shared_ptr的方法
shared_ptr<T> p(q) //p管理内置指针q所指向的对象;q必须指向new分配的内存,且能够转换为T*类型
shared_ptr<T> p(u) //p从unique_ptr u那里接管了对象的所有权;将u置为空
shared_ptr<T> p(q, d) //p接管了内置指针q所指向的对象的所有权。q必须能转换为T*类型。p将使用可调用对象d来代替delete。
shared_ptr<T> p(p2, d) //p是shared_ptr p2的拷贝,唯一的区别是p将可调用对象d来代替delete。
p.reset() //若p是唯一指向其对象的shared_ptr,reset会释放此对象。若传递了可选的参数内置指针q,会令p指向q,否则会将p置空。若还传递了参数d,则会调用d而不是delete来释放q。
p.reset(q) //同上
p.reset(q, d) //同上
//不要混合使用普通指针和智能指针
void process(shared_ptr<int> ptr){
//使用ptr
}//ptr离开作用域,被销毁
//值传递,会拷贝,process运行过程中,引用计数值至少为2,process结束,ptr引用计数会递减但不会变为0,因此当局部ptr被销毁时,ptr指向的内存不会被释放
shared_ptr<int> p(new int(42));
process(p);
int i = *p;
//虽不能传递给process一个内置指针,但可以传递一个临时的shared_ptr。
int *x(new int(42));
process(x); //错误,不能转换int*为shared_ptr<int>
process(shared_ptr<int>(x));
int j = *x;//未定义的:x是一个空悬指针。
//临时对象当这个调用所在的表达式结束时就被销毁了。引用计数变为0,内存被释放。但x继续指向已经释放的内存,从而变为一个空悬指针。
//不要用get初始化另一个智能指针或为智能指针赋值。
//智能指针类型定义了一个名为get的函数,它返回一个内置指针,指向智能指针管理的对象。使用get返回的指针的代码不能delete此指针。
shared_ptr<int> p(new int(42));
int *q = p.get();
{
shared_ptr<int> q;
}
int foo = *p;//未定义的,p为空悬指针
//p和q指向相同的内存,它们是相互独立创建的,因此各自的引用计数都为1。q所在程序块结束时,q被销毁,导致q指向的内存被释放。p被销毁时,这块内存会被第二次delete.
//其他shared_ptr操作
p = new int(1024);//wrong
p.reset(new int(1024));//right,p指向一个新对象
//与赋值类似,reset会更新引用计数,如需要会释放p指向的对象。
if(!p.unique()){
p.reset(new string(*p));//我们不是唯一用户,分配新的拷贝
}
*p += newVal;//现直到自己是唯一用户,可以改变对象的值。
智能指针与异常
- 使用智能指针即使程序块过早结束,也能确保在内存不在需要时将其释放。
void f(){
shared_ptr<int> sp(new int(42));
}
void f(){
int *ip = new int(42);
delete ip;
}
struct destination;
struct connection;
connection connect(destination*);
void disconnect(connection);
void f(destination &d){
connection c = connect(&d);
}
void end_connection(connection *p){disconnect(*p);}
void f(destination& d){
connection c = connect(&d);
shared_ptr<connection> p(&c,end_connection);
}
智能指针的陷阱和规范
- 不使用相同的内置指针初始化或reset多个智能指针。
- 不delete get()返回的指针
- 不使用get()初始化或reset另一个智能指针。
- 如果你使用get()返回的指针,记住当最后一个对应的智能指针销毁后,你的指针就变的无效了。
- 如果你使用智能指针管理的资源不是new分配的内存,记住传递给它一个删除器。
unique_ptr
- 一个unique_ptr拥有它所指向的对象,某一个时刻只能有一个unique_ptr指向一个给定的对象。需要绑定到一个new返回的指针上,初始化unique_ptr必须采用直接初始化形式。
unique_ptr<double> p1;
unique_ptr<int> p2(new int(42));
unique_ptr<string> p1(new string("Stegosaurus"));
unique_ptr<string> p2(p1);
unique_ptr<string> p3;
p3 = p2;
unique_ptr<T> u1
unique_ptr<T, D> u2
unique_ptr<T, D> u(d)
u = nullptr
u.release()
u.reset()
u.reset(q)
u.reset(nullptr)
unique_ptr<string> p2(p1.release());
unique_ptr<string> p3(new string("Trex"));
p2.reset(p3.release());
p2.release();
auto p = p2.release();
unique_ptr<int> clone(int p){
return unique_ptr<int>(new int(p));
}
unique_ptr<int> clone(int p){
unique_ptr<int> ret(new int (p));
...
return ret;
}
unique_ptr<objT,delT> p(new objT,fcn);
void f(destination &d){
connection c = connect(&d);
unique_ptr<connection,decltype(end_connection)*> p(&c,end_connection);
}
weak_ptr
- weak_ptr是一种不控制所指向对象生存期的智能指针。
- 指向一个由shared_ptr管理的对象,不改变shared_ptr的引用计数。
- 一旦最后一个指向对象的shared_ptr被销毁,对象就会被释放,不管有没有weak_ptr指向该对象。
weak_ptr操作
weak_ptr<T> w
weak_ptr<T> w(sp)
w = p
w.reset()
w.use_count()
w.expired()
w.lock()
auto p = make_shared<int>(42);
weak_ptr<int> wp(p);
if(shared_ptr<int> np = wp.lock()){
}
核查指针类
class StrBlobPtr{
public:
StrBlobPtr():curr(0){}
StrBlobPtr(StrBlob &a,size_t sz = 0):wptr(a.data),curr(sz){}
std::string& deref() const;
StrBlobPtr& incr();
private:
std::shared_ptr<std::vector<std::string>> check(std::size_t,const std::string&) const;
std::weak_ptr<std::vector<std::string>> wptr;
std::size_t curr;
};
std::shared_ptr<std::vector<std::string>> StrBlobPtr::check(std::size_t i,const std::string &msg) const{
auto ret = wptr.lock();
if(!ret)
throw std::runtime_error("unbound StrBlobPtr");
if(i >= ret->size())
throw std::out_of_range(msg);
return ret;
}
std::string& StrBlobPtr::deref() const{
auto p = check(curr,"dereference past end");
return (*p)[curr];
}
StrBlobPtr& StrBlobPtr::incr(){
check(curr,"increment past end of StrBlobPtr");
++curr;
return *this;
}
classs StrBlobPtr;
class StrBlob{
friend class StrBlobPtr;
StrBlobPtr begin() {return StrBlobPtr(*this);}
StrBlobPtr end(){
auto ret = StrBlobPtr(*this,data->size());
return ret;
}
};
动态数组
int *pia = new int[get_size()];
typedef int arrT[42];
int *p = new arrT;
int *pia = new int[10];
int *pia2 = new int[10]();
string *psa = new string[10];
string *psa2 = new string[10]();
int *pia3 = new int[10]{0,1,2,3,4,5,6,7,8,9};
string *psa3 = new string[10]{"a","an","the",string(3,'x')};
size_t n = get_size();
int *p = new int[n];
for(int *q=p;q!=p+n;++q){}
char arr[0];
char *cp = new char[0];正确,但cp不能解引用
delete p;
delete [] pa;
typedef int arrT[42];
int *p = new arrT;
delete [] p;
unique_ptr<int[]> up(new int[10]);
up.release();
for(size_t i = 0;i!=10;++i){
up[i] = i;
}
unique_ptr<T[]> u
unique_ptr<T[]> u(p)
u[i]
shared_ptr<int> sp(new int[10],[](int *p){delete [] p;});
sp.reset();
for(size_t i = 0;i!=10;++i){
*(sp.get() + i) =i;
}
allocator类(分配和初始化分离)
- 标准库allocator类定义在头文件memory中,帮助我们将内存分配和对象构造分离开。
- 分配的是原始的、未构造的内存。
string *const p = new string[n];
string s;
string *q = p;
while(cin>>s && q!=p+n)
*q++ = s;
const size_t size = q - p;
delete[] p;
allocator<string> alloc;
auto const p = alloc.allocate(n);
allocator<T> a
a.allocate(n)
a.deallocate(p, n)
a.construct(p, args)
a.destroy(p)
auto q = p;
alloc.construct(q++);
alloc.construct(q++,10,'c');
alloc.construct(q++,"hi");
cout<<*p<<endl;
cout<<*q<<endl;
while(q!=p)
alloc.destroy(--q);
alloc.deallocate(p,n);
拷贝和填充未初始化内存的算法,头文件memory中
uninitialized_copy(b, e, b2)
uninitialized_copy_n(b, n, b2)
uninitialized_fill(b, e, t)
uninitialized_fill_n(b, n, t)
auto p = alloc.allocate(vi.size()*2);
auto q = uninitialized_copy(vi.begin(),vi.end(),p);
uninitialized_fill_n(q,vi.size(),42);
使用标准库:文本查询程序
void runQueries(ifstream &infile){
TextQuery tq(infile);
while(true){
cout<<"enter word to look for,or q to quit:";
string s;
if(!(cin>>s) || s == 'q') break;
print(cout,tq.query(s)) <<endl;
}
}
class QueryResult;
class TextQuery{
public:
using line_no = std::vector<std::string>::size_type;
TextQuery(std::ifstream&);
QueryResult query(const std::string&) const;
private:
std::shared_ptr<std::vector<std::string>> file;
std::map<std::string,std::shared_ptr<std::set<line_no>>> wm;
};
TextQuery::TextQuery(ifstream &is):file(new vector<string>){
string text;
while(getline(is,text)){
file->push_back(text);
int n = file->size() - 1;
istringstream line(text);
string word;
while(line>>word){
auto &lines = wm[word];
if(!lines)
lines.reset(new set<line_no>);
lines->insert(n);
}
}
}
class QueryResult{
friend std::ostream& print(std::ostream&,const QueryResult&);
public:
QueryResult(std::string s,std::shared_ptr<std::set<line_no>> p,std::shared_ptr<std::vector<std::string>> f):sought(s),lines(p),file(f){}
private:
std::string sought;
std::shared_ptr<std::set<line_no>> lines;
std::shared_ptr<std::vector<std::string>> file;
}
QueryResult TextQuery::query(const string &sought) const{
static shared_ptr<set<line_no>> nodata(new set<line_no>);
auto loc = wm.find(sought);
if(loc == wm.end())
return QueryResult(sought,nodata,file);
else
return QueryResult(sought,loc->second,file);
}
ostream& print(ostream &os,const QueryResult &qr){
os<<qr.sought<<"occurs"<<qr.lines->size()<<" "<<make_plural(qr.lines->size(),"times","s")<<endl;
for(auto num : *qr.lines)
os<<"\t(line"<<num+1<<")"<<*(qr.file->begin()+num)<<endl;
return os;
}