版权声明:
本系列博客是王健伟老师大作《c++新经典》的学习笔记,c++初学者及想深入了解c++的朋友可以买来阅读。
函数返回指针或者引用听着很简单,其实里面有坑,关键在于,返回的指针有没有被释放,还可不可以用。
下面,我们边看代码边分析。
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
string name;
Person(string _name);
~Person();
};
Person::Person(string _name)
{
name = _name;
}
Person::~Person()
{
}
Person* GetPerson1()
{
Person p("p1");
cout << "GetPerson1 p1地址:" << &p << endl;
return &p;
}
Person& GetPerson2()
{
Person p("p2");
cout << "GetPerson2 p2地址:" << &p << endl;
return p;
}
Person* GetPerson3()
{
Person* p = new Person("p3");
cout << "GetPerson3 p3地址:" << &p << endl;
cout << "GetPerson3 p3指向对象的地址:" << &(*p) << endl;
return p;
}
int main()
{
Person* p1 = GetPerson1();
cout << "Main函数p1地址:" << p1 << endl;
cout << "----------------------" << endl;
Person& p2 = GetPerson2();
cout << "Main函数p2地址:" << &p2 << endl;
cout << "----------------------" << endl;
Person* p3 = GetPerson3();
cout << "Main函数p3地址:" << p3 << endl;
cout<< "Main函数p3指向对象的地址:" << &(*p3) << endl;
cout << "----------------------" << endl;
cout << "Over" << endl;
delete p3;
}
运行结果如下
对象p1和p2都是函数内部在栈上分配的对象地址,函数执行结束后,已经释放了,main函数不能使用这块被释放的内存,因为这块内存可能已经被系统分配出去。
p3的函数内对象地址和main函数对象地址是不同的,不会使用已经释放的内存,函数内的对象是new出来的,需要手动释放,也不用担心对象被自动释放问题。
虽然直接在栈上创建对象,对象自动释放,但是,要注意自动释放带来的坑,相反,堆上创建对象,就要注意对象不要忘记释放的问题。