智能指针和普通指针的用法类似,但是智能指针可以在适当时机自动释放分配的内存。
C++11有三种类型的智能指针,shared_ptr、unique_ptr 以及 weak_ptr;
先学习shared_ptr类型;
shared_ptr
T 表示指针指向的具体数据类型;
C++11 还提供了 std::make_shared
shared_ptr
其中;get(),获得 shared_ptr 对象内部包含的普通指针;
use_count(), 返回引用计数;
- #include
- #include
-
- using namespace std;
-
- int main()
- {
- std::shared_ptr<int> p1(new int(9999));
- std::shared_ptr
s1(new string("test string")) ; -
- cout << p1 << ", 引用计数:" << p1.use_count() << endl;
- cout << s1 << ", 引用计数:" << s1.use_count() << endl;
-
- auto a1 = std::make_shared<int>(9979);
- co