系列文章目录
前言
一、智能指针是什么?
智能指针是C++11新特性,智能指针主要用来管理在堆上分配的内存,它将普通的指针封装为一个栈对象,当栈对象生存周期结束后,会在析构函数中释放申请的内存,防止内存泄露。
C++11引入智能指针,方便管理堆内存。普通指针需要手动申请和释放内存,使用智能指针不需要关心对象内存申请和释放,可有效避免堆内存泄漏问题(忘记释放)。
其采用了一种RAII技术,RAII是一种了利用对象生命周期来控制程序资源(如:内存,文件,套接字,互斥量等)的技术。
通常我们都是通过对象管理指针的方式,但是智能智能对象都是栈上分配,一出作用域就会引用技数减1,当引用计数为0时,会释放资源,但是有时候需要将智能指针对象作为参数传递,且参数类型为void*,传递的并非类对象,而是void*,指针对象被释放,进入workThreadEntry,此时就会出现问题。
void workerThreadEntry(void *ptr){
}
std::shared_ptr<A> aA= std::make_shared<A>();
std::thread(std::bind(&workThreadEntry, aA.get()));
下面通过new智能指针对象来解决这个问题。
void workerThreadEntry(void *ptr){
}
std::shared_ptr<A> aA= std::make_shared<A>(); //计数1
void *p = new std::shared_ptr<A>(aA); //计数2
std::thread(std::bind(&workThreadEntry, p)); //进入workThreadEntry函数后,转换后,计数3
二、使用步骤
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <map>
#include <memory>
#include <cmath>
class A
{
public:
A(){
}
~A(){
}
A(const A &) = delete;
A &operator=(const A &) = delete;
};
void test(void *p)
{
std::shared_ptr<A> aA = *static_cast<std::shared_ptr<A> *>(p);
std::cout << "3 counting:" << aA.use_count() <<std::endl;
}
int main()
{
{
std::shared_ptr<A> aA = std::make_shared<A>(); //引用计数+1
std::cout << "1 counting:" << aA.use_count() <<std::endl;
void *p = new std::shared_ptr<A>(aA); //引用计数+1
std::cout << "2 counting:" << aA.use_count() <<std::endl;
test(p);
delete static_cast<std::shared_ptr<A> *>(p); //引用计数-2
std::cout << "4 counting:" << aA.use_count() <<std::endl;
aA.reset(); //引用计数-1
std::cout << "5 counting:" << aA.use_count() <<std::endl;
}
getchar();
return 0;
}
运行结果如下:
[root@localhost DAVITTEST]# ./test
1 counting:1
2 counting:2
3 counting:3
4 counting:1
5 counting:0
总结
通过上面的介绍,应该对new shared_ptr有了一定的认识,希望对你有所帮助。