参考网站:http://www.cplusplus.com/reference/
一、auto_ptr
原型:template class auto_ptr;
由于存在潜在的内存崩溃问题,却不能在编译期间发现所以已经被C++11废弃了,但仍然有一定的学习意义,下面是一些成员函数及其简介:
- get:得到对象类管理的对象指针
- operator*:得到管理的对象
- operator->:等价于
(*class).
,用于获取对象的某个成员 - release:将管理对象的指针返回并设置类内指针为null
- operator= :相当于调用release之后将返回值构造为新的类初始化左边的类,Release and copy auto_ptr
- reset:若无参数直接释放当前对象否则用参数重新设置当前值,无返回值
#include <iostream>
#include <memory>
int main () {
std::auto_ptr<int> p;
p.reset (new int);
*p=5;
std::cout << *p << '\n';//*p=5
int *x=p.release ();
*x=10;
std::cout << *x << '\n';//*x=10
std::auto_ptr<int> s(x);
*s=15;
std::cout << *s << '\n';//*s=15
std::cout << *p << '\n';//前面已经释放,此处报错
return 0;
}
二、std::shared_ptr
原型:template class shared_ptr;
成员函数,多了引用计数,有些操作同auto_ptr操作:
- operator=:shared_ptr assignment (public member function )
- swap:Swap content (public member function )
- reset:Reset pointer (public member function )
- get:Get pointer (public member function )
- operator*:Dereference object (public member function )
- operator->:Dereference object member (public member function )
- use_count:Use count (public member function )
- unique:Check if unique (public member function )
- operator bool:Check if not null
非成员函数: make_shared
template <class T, class… Args>
shared_ptr make_shared (Args&&… args);
返回一个类型为T的被初始化了的shared_ptr对象。
#include <iostream>
#include <memory>
int main () {
std::shared_ptr<int> foo = std::make_shared<int> (10);
// same as:
std::shared_ptr<int> foo2 (new int(10));
auto bar = std::make_shared<int> (20);
auto baz = std::make_shared<std::pair<int,int>> (30,40);
std::cout << "*foo: " << *foo << '\n';
std::cout << "*bar: " << *bar << '\n';
std::cout << "*baz: " << baz->first << ' ' << baz->second << '\n';
return 0;
}
三、unique_ptr
//non-specialized
template <class T, class D = default_delete<T>> class unique_ptr;
//array specialization
template <class T, class D> class unique_ptr<T[],D>;
相比于auto_ptr,其可以在编译期间合理确定智能指针对象作为右值时的合法性,只有作为临时右值才合法否则报错。
// unique_ptr::swap example
#include <iostream>
#include <memory>
int main () {
std::unique_ptr<int> foo (new int(10));
std::unique_ptr<int> bar (new int(20));
foo.swap(bar);
std::cout << "foo: " << *foo << '\n';
std::cout << "bar: " << *bar << '\n';
return 0;
}
四、std::weak_ptr
原型:template class weak_ptr;
- operator=:weak_ptr assignment (public member function )
- swap:Swap content (public member function )
- reset:Reset pointer (public member function )
- use_count:共享shared_ptr的指针数
- expired:看对象use_count计数,若>0返回真
- lock:返回其指示的shared_ptr对象
- owner_before:Owner-based ordering (public member function template )
// weak_ptr::lock example
#include <iostream>
#include <memory>
int main () {
std::shared_ptr<int> sp1,sp2;
std::weak_ptr<int> wp;
// sharing group:
// --------------
sp1 = std::make_shared<int> (20); // sp1
wp = sp1; // sp1, wp
sp2 = wp.lock(); // sp1, wp, sp2
sp1.reset(); // wp, sp2
sp1 = wp.lock(); // sp1, wp, sp2
std::cout << "*sp1: " << *sp1 << '\n';
std::cout << "*sp2: " << *sp2 << '\n';
return 0;
}