#include "stdafx.h"
#include <iostream>
#include <future>
#include <thread>
using namespace std;
class Person
{
public:
Person(int v) {
value = v;
std::cout << "Cons" <<value<< std::endl;
}
~Person() {
std::cout << "Des" <<value<< std::endl;
}
int value;
};
int main()
{
std::shared_ptr<Person> p1(new Person(1));// Person(1)的引用计数为1
std::shared_ptr<Person> p2 = std::make_shared<Person>(2);
p1.reset(new Person(3));// 首先生成新对象,然后引用计数减1,引用计数为0,故析构Person(1)
// 最后将新对象的指针交给智能指针
std::shared_ptr<Person> p3 = p1;//现在p1和p3同时指向Person(3),Person(3)的引用计数为2
p1.reset();//Person(3)的引用计数为1
p3.reset();//Person(3)的引用计数为0,析构Person(3)
return 0;
}
int *p5 = new int;
std::shared_ptr<int> p6(p5);
std::shared_ptr<int> p7(p5);// logic error
// 错
function(shared_ptr<int>(new int), g());
#include <iostream>
#include <memory>
using namespace std;
class A{
public:
string id;
A(string id):id(id){cout<<id<<":构造函数"<<endl;}
~A(){cout<<id<<":析构函数"<<endl;}
};
int main() {
unique_ptr<A> a(new A("unique_ptr"));
shared_ptr<A> b = move(a);
// a = move(b); // 报错
// a.reset(b.get()); // 运行错误
cout<<a.get()<<endl;
return 0;
}
#include <iostream>
#include <memory>
using namespace std;
class A{
public:
string id;
A(string id):id(id){cout<<id<<":构造函数"<<endl;}
~A(){cout<<id<<":析构函数"<<endl;}
};
A a("全局变量");
int main() {
A b("局部变量");
// unique_ptr<A> pa(&a); // 运行错误
unique_ptr<A> pa(&b);
return 0;
}
原文:https://www.cnblogs.com/sjl473/p/14255830.html