智能指针
shared_ptr 主对象结构体
shared 指针类似于一个带计数器的指针,当指针计数次数为0时,它将自动析构对象。
shared_ptr指针可通过一次new出来,一直向下传递,直到每次析构shared_ptr时将该指针引用量-1
注:每次进行不带引用的传递时调用次数会加1,但析构时同时会-1,若用引用传递,每次调用值不增加,但同样析构时值也不减小。
我是一个标签
#include <boost/make_shared.hpp>
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace boost;
class FA{
public:
int func(){
printf(" i don't konw yy\n");
return 0;
}
};
int foo1(shared_ptr<FA> pfa){
printf("foo1:the count is %ld\n",pfa.use_count());
return 0;
}
shared_ptr<FA>& foo2(shared_ptr<FA>& pfa){
printf("foo2:the count is %ld\n",pfa.use_count());
return pfa;
}
int main(){
shared_ptr<FA> pfa(new FA());
foo1(pfa);//first called print 2
foo1(pfa);//second called print 2
foo1(foo2(pfa));//foo2:1 foo1:2
return 0;
}
make_share 便捷new出对象
由于上边的方式仍有多处new使得程序不平衡,因此改用make_shared.注意make_shared 为指针类型,数组类型慎用。
#include <iostream>
#include <boost/make_shared.hpp>
#include <string>
#include <vector>
#include <list>
using namespace std;
using namespace boost;
int main(){
//make_shared shuld use the boost:: ,because the std lib also have
auto sp1 = boost::make_shared<string>();
//is mine int[10] and int[0,1,2..]=2
auto sp2 = boost::make_shared<vector<int> >(10,2);
//there std::
std::cout <<"string:"<< sp1->c_str()
<<"vector size:"<<sp2->size()
<<std::endl;
}
make_shared 使用中的注意事项
- make_shared 内部统计一个引用次数的变量,每次析构会-1,
当引用次数为0时会析构该对象,根据目前测试结果,该对象
以引用方式返回时次数不减小,即可封入函数中进行操作。 - make_shared 返回为shared_ptr类型对象,该对象对自身
成员函数重载了’.’如t1.use_count()。对new出的变量重载了’->’
,即t1->length()。注意如果要使用new出变量的重载操
作符时要对shared_ptr进行取址,否则会使用智能指针本身的重载。
#include <cstdlib>
#include <boost/make_shared.hpp>
#include <iostream>
using namespace std;
using namespace boost;
//注意该处类型
boost::shared_ptr<int> create_entity(){
auto t2 = boost::make_shared<int>(5);
return t2;
}
int main(int argc, char** argv) {
auto t1 = boost::make_shared<string>("what 1 is bad");
*t1 += "so bad laaa"; //通过取址可以使用原变量重载的操作符
std::cout<<" the value is "<<*t1<<std::endl
<<"the return count is"<<t1.use_count() //智能指针本身的函数需用.调用
//<<" and "<<t1->use_count() //error:智能指针将->重载为原变量的的成员调用
<<t1->size() <<std::endl //使用->可调用原函数
;
auto t2 = create_entity();
std::cout<<"the return count is"<<t2.use_count()
<<" the value is "<<*t2<<std::endl;
//打印:1 5 说明智能指针如果做了返回值得话次数不减小。
return 0;
}
这确实是一个标签
weak_ptr 智能指针跟踪
#include <boost/make_shared.hpp>
#include <boost/smart_ptr.hpp>
#include <iostream>
using namespace std;
using namespace boost;
int main(){
auto p1 =boost::make_shared<int>(5);
std::cout << *p1 <<std::endl;
boost::weak_ptr<int> wp(p1);
if(!wp.expired()){
boost::shared_ptr<int> sp2 = wp.lock();
*sp2 = 100;
assert(wp.use_count() == 2);
}
assert(wp.use_count() == 1);
p1.reset();
if(wp.expired() == false)
std::cout<<"source point is lose effcacy"<<std::endl;
//当指针被重置之后该处将返回失败
if(wp.lock() == NULL)
std::cout<<"get the source address is nullptr"<<std::endl;
}