class 内存分配与释放
#include <iostream>
#include <memory>
using namespace std;
class Person {
public:
Person() {
cout << "person constructor" << endl;
}
~Person()
{
cout << "person destructor" << endl;
}
void sayHello()
{
cout << "person say hello" << endl;
}
};
static void f1()
{
cout << "不用指针:" << endl;
auto p = Person();
}
static void f2() {
cout << "new/delete:" << endl;
auto p = new Person();
delete p;
}
static void f3() {
cout << "unique_ptr:" << endl;
auto p = make_unique<Person>();
}
static void f5(const shared_ptr<Person> & p) {
p->sayHello();
}
static void f4()
{
cout << "shared_ptr 传参:" << endl;
auto p = make_shared<Person>();
f5(p);
p->sayHello();
}
static void f6(const unique_ptr<Person>& p) {
p->sayHello();
}
static void f5() {
cout << "unique_ptr 传参:" << endl;
auto p = make_unique<Person>();
f6(p);
p->sayHello();
}
int main()
{
f1();
cout << "================================" << std::endl;
f2();
cout << "================================" << std::endl;
f3();
cout << "================================" << std::endl;
f4();
cout << "================================" << std::endl;
cout << "shared_ptr" << endl;
f5();
return 0;
}
输出
不用指针:
person constructor
person destructor
================================
new/delete:
person constructor
person destructor
================================
unique_ptr:
person constructor
person destructor
================================
shared_ptr 传参:
person constructor
person say hello
person say hello
person destructor
================================
shared_ptr
unique_ptr 传参:
person constructor
person say hello
person say hello
person destructor