目录
自从c++11引入智能指针shared_ptr后,我们似乎再也不用担心new的内存没有释放之类的问题了,但是也带来了其他的问题。
shared_ptr
智能指针是指向动态分配(堆)对象的指针,用于生存期控制,能确保自动正确的销毁动态分配的对象,防止内存泄露。它的一种通用实现技术是使用引用计数。每次使用它,内部引用计数加1,每析构一次,内部引用计数减1,减为0时,删去所指向的堆内存。
C++11中的智能指针包括:
std::shared_ptr
std::unique_ptr
std::weak_ptr
其中最常用的就是std::shared_ptr。每个shared_ptr的拷贝都指向相同的内存.最后一个shared_ptr析构的时候,堆中的内存才会被释放。share_ptr类型的对象具有获得指针所有权并共享所有权的能力。
初始化:
可以通过指针来初始化它:template <class U> explicit shared_ptr (U *p);
std::shared_ptr<int>p(new int(2));
std::shared_ptr<int>p2= p;
std::shared_ptr<BaseConnector> m_connt = make_shared<Connector>(m_ios, m_strIP, m_port);
通过构造函数、赋值函数或者 make_shared 函数初始化智能指针。
例子:
// shared_ptr constructor example
#include <iostream>
#include <memory>
struct C {int* data;};
int main () {
std::shared_ptr<int> p1;
std::shared_ptr<int> p2 (nullptr);
std::shared_ptr<int> p3 (new int);
std::shared_ptr<int> p4 (new int, std::default_delete<int>());
std::shared_ptr<int> p5 (new int, [](int* p){delete p;}, std::allocator<int>());
std::shared_ptr<int> p6 (p5);
std::shared_ptr<int> p7 (std::move(p6));
std::shared_ptr<int> p8 (std::unique_ptr<int>(new int));
std::shared_ptr<C> obj (new C);
std::shared_ptr<int> p9 (obj, obj->data);
std::cout <