#include <iostream>
#include <vector>
using namespace std;
class person
{
public:
person(int a) : age(a) {}
~person() { cout << "Destructor called." << endl; }
void display()
{
cout << "age : " << age << endl;
}
private:
int age;
};
int main()
{
/*创建person类型的对象 并用construct分配一个对象给指针p*/
allocator<person> alloc;
person *p = alloc.allocate(1);
alloc.construct(p, person(10)); //临时对象会自动析构,调用析构函数
p->display();
alloc.destroy(p); //调用destroy只会调用析构函数而不会释放内存
p->display(); //因为没有释放内存,并且我的析构函数什么都没做,所以还可以输出10
alloc.deallocate(p, 1); //此处释放了p所指向的内存
p->display(); //因为释放了内存,所以p所指向的内存中数据未知
return 0;
}
#include <vector>
using namespace std;
class person
{
public:
person(int a) : age(a) {}
~person() { cout << "Destructor called." << endl; }
void display()
{
cout << "age : " << age << endl;
}
private:
int age;
};
int main()
{
/*创建person类型的对象 并用construct分配一个对象给指针p*/
allocator<person> alloc;
person *p = alloc.allocate(1);
alloc.construct(p, person(10)); //临时对象会自动析构,调用析构函数
p->display();
alloc.destroy(p); //调用destroy只会调用析构函数而不会释放内存
p->display(); //因为没有释放内存,并且我的析构函数什么都没做,所以还可以输出10
alloc.deallocate(p, 1); //此处释放了p所指向的内存
p->display(); //因为释放了内存,所以p所指向的内存中数据未知
return 0;
}
本文详细介绍了C++中对象的创建、生命周期管理及析构过程,通过实例展示了使用allocator和construct函数分配和初始化对象的过程,以及如何正确地销毁和释放内存。
320

被折叠的 条评论
为什么被折叠?



