对象回收实验
对象被释放时,成员变量(不是new出来的)会被自动释放
#include <iostream>
#include <memory>
using namespace std;
class Cat {
public:
int age;
~Cat() { cout << "~Cat" << endl; }
};
class Person {
public:
int age;
Cat cat;
~Person() { cout << "~person" << endl; }
};
void test1(Cat &cat) {}
int main() {
// { shared_ptr<Person> ptr = make_shared<Person>(); }
Person *p = new Person();
delete p;
}
打印:
~person
~Cat
vector push_back会发生拷贝构造
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class Cat {
public:
int age;
~Cat() { cout << "~Cat" << endl; }
Cat() { cout << "Cat" << endl; }
Cat(const Cat &cat) { cout << "Cat copy" << endl; }
};
class Person {
public:
int age;
Cat cat;
~Person() { cout << "~person" << endl; }
};
int main() {
// { shared_ptr<Person> ptr = make_shared<Person>(); }
Person p;
{
vector<Person> v;
v.push_back(p);
}
cout << "vector over !" << endl;
}
打印
Cat
Cat copy
~person
~Cat
vector over !
~person
~Cat

浙公网安备 33010602011771号