/*******shared_ptr:变量出了作用域之后智能指针会析构,引用计数-1,直到为0时销毁对象,调用对象的析构函数,哪怕是出现了异常。*****/
/*******weak_ptr解决循环引用问题*******/
/*******unique_ptr它不允许其他的智能指针共享其内部的指针,不允许通过赋值将一个unique_ptr赋值给另一个unique_ptr*/
以shared_ptr为例:
class Test
{
public:
Test(string x) : m_x(x) {
cout << "Init" << endl;
};
~Test() {
cout << "destyoy " << m_x.c_str() << endl;
};
string getId() const {
return m_x;
}
void setId(string x) {
m_x = x;
}
private:
string m_x;
};
class Thistest : public enable_shared_from_this<Thistest>
{
public:
shared_ptr<Thistest> f() {
return shared_from_this();
}
private:
};
int main()
{
//智能指针初始化
//shared_ptr<Test> p = make_shared<Test>("0");
//shared_ptr<Test> s_ptr(p); //赋值操作,引用计数加1
//Test *t = new Test("a");
//shared_ptr<Test> s_ptr(t); //用原始指针初始化
//cout << "s_ptr : " << s_ptr.use_count() << endl;
//s_ptr.reset(new Test("b")); //所指的对象会被重置,不带参数则是销毁
//cout << "s_ptr : " << s_ptr.use_count() << " " << (*s_ptr).getId().c_str() << endl;
shared_ptr<Test> s_ptr1(new Test("c"));
//shared_ptr<Test> s_ptr1 = new Test(1); //错误:不能将一个原始指针赋予shared_ptr
cout << "s_ptr1 : " << s_ptr1.use_count() << " "
<<s_ptr1->getId().c_str() << endl; //1 c
{//用花括号控制指针的作用域或生命周期
shared_ptr<Test> s_ptr2(s_ptr1); //调用拷贝构造 +1
cout << "s_ptr2 : " << s_ptr2.use_count() << " "<< (*s_ptr2).getId().c_str() << endl; //2 c
(*s_ptr2).setId("d");
{
shared_ptr<Test> s_ptr3 = s_ptr1; //调用赋值操作符
cout << "s_ptr3 : " << s_ptr3.use_count() << " "<< (*s_ptr3).getId().c_str() << endl; //3 d
//s_ptr3.reset();
}
cout << "s_ptr1 : " << s_ptr1.use_count() << " "<< (*s_ptr1).getId().c_str() << endl; //2 d
}
//shared_ptr<Test> s_ptr4;
//swap(s_ptr4, s_ptr2);
cout << "s_ptr1 : " << s_ptr1.use_count() << " "<< (*s_ptr1).getId().c_str() << endl; //1 d
Test *pp = s_ptr1.get();
if (pp) {
cout << pp->getId().c_str() << endl;
}
delete pp; //获取原始指针后不能释放,如果释放会出错。
//不要用一个原始的指针初始化多个shared_ptr
//想用this指针时,利用std::enable_shared_from_this<Y>,然后使用shared_from_this()构造shared_ptr。
shared_ptr<Thistest> pt1(new Thistest());
shared_ptr<Thistest> pt2 = pt1->f(); // pt2是由pt1的this构造共享智能指针
std::cout << pt1.use_count() << " " << pt2.use_count() << std::endl; // 2 2
shared_ptr<Thistest> pt3(new Thistest());
shared_ptr<Thistest> pt4 = pt3->f();
std::cout << pt1.use_count() << " " << pt2.use_count() << " "
<< pt3.use_count() << " " << pt4.use_count() << std::endl; // 2 2 2 2
system("pause");
return 0;
}