例子做了修改:
#include <iostream>
#include <memory>
using namespace std;
class B; //声明
class A
{
public:
shared_ptr<B> pb_;
~A()
{
cout << "A delete\n";
}
};
class B
{
public:
shared_ptr<A> pa_;
~B()
{
cout << "B delete\n";
}
};
void test_w()
{
shared_ptr<B> pb(new B());
shared_ptr<A> pa(new A());
cout << pb.use_count() << endl; //1
cout << pa.use_count() << endl; //1
pb->pa_ = pa;
pa->pb_ = pb;
cout << pb.use_count() << endl; //2
cout << pa.use_count() << endl; //2
}
void test_shared()
{
string *s1 = new string("s1");
shared_ptr<string> ps1(s1);
shared_ptr<string> ps2;
cout << ps1.unique() << endl;
cout << ps2.unique() << endl;
ps2 = ps1;
cout << ps1.use_count()<<endl; //2
cout<<ps2.use_count()<<endl; //2
cout << ps1.unique()<<endl; //0
string *s3 = new string("s3");
shared_ptr<string> ps3(s3);
cout << (ps1.get()) << endl; //033AEB48
cout << ps3.get() << endl; //033B2C50
cout << ps1.use_count() << endl;
cout << ps3.use_count() << endl;
cout << __LINE__ << "_ps1:" << *ps1 << endl;
cout << __LINE__ << "_ps3:" << *ps3 << endl;
cout << __LINE__ << "_ps2:" << *ps2 << endl;
swap(ps1, ps3); //交换所拥有的对象
cout << (ps1.get())<<endl; //033B2C50
cout << ps3.get() << endl; //033AEB48
cout << __LINE__ << "_ps1:" << *ps1 << endl;
cout << __LINE__ << "_ps3:" << *ps3 << endl;
cout << ps1.use_count()<<endl; //1
cout << ps2.use_count() << endl; //2
ps2 = ps1;
cout << __LINE__ << "_ps2:" << *ps2 << endl;
cout << __LINE__ << "_ps1:" << *ps1 << endl;
cout << ps1.use_count()<<endl; //2
cout << ps2.use_count() << endl; //2
ps1.reset(); //放弃ps1的拥有权,引用计数的减少
cout << ps1.use_count()<<endl; //0
cout << ps2.use_count()<<endl; //1
}
int test2()
{
//初始化方式1
std::unique_ptr<int> up1(new int(123));
//初始化方式2
std::unique_ptr<int> up2;
up2.reset(new int(456));
//初始化方式3 (-std=c++14)
std::unique_ptr<int> up3 = std::make_unique<int>(789);
cout << *up1 << " " << *up2 << " " << *up3 << endl;
}
class Complex
{
private:
int Real;
int Image;
public:
~Complex(){cout << "_Destory_" << __LINE__ << endl;}
Complex(int r,int i):Real(r),Image(i){cout << "_Creat_" << __LINE__ << endl;}
Complex(const Complex& c):Real(c.Real),Image(c.Image){cout << "_Creat_cp_" << __LINE__ << endl;}
};
void Fun(Complex c1)
{
}
Complex Fun2()
{
Complex c(10,20);
return c;
}
void test3()
{
cout << "c1:" << endl;
Complex c1(1,2);
cout << "Fun(c1):" << endl;
Fun(c1);
cout << "c2:" << endl;
Complex c2 = Fun2();
cout << "c3:" << endl;
Complex &c3 = c2;
cout << "c4:" << endl;
Complex c4 = c3;
cout << "c5:" << endl;
Complex c5(c4);
cout << "c5 value:" << endl;
}
int main()
{
test3();
test2();
test_w();
//test_shared();
/*
unique_ptr<string> ps1, ps2;
ps1 = unique_ptr<string>(new string ("Hello"));
ps2 = move(ps1);
ps1 = unique_ptr<string>(new string ("nihao"));
cout << *ps2 << " " << *ps1 << endl;
*/
return 0;
}
|