The Leak of the Memory in C++
In this chaper I will introduce a new smart pointer which is scoped_ptr;
It likes auto_ptr but better. When peopel use auto_ptr, sometimes they forget
that auto_ptr alread is empty, like this;
auto_ptrp1(new Person); auto_ptr p2 = p1; cout << p1->name() << endl;
class PersonImpl { public: PersonImpl() { cout << "I'm constructed" << endl; } ~PersonImpl() { cout << "I'm destructed!" << endl; } private: int age_; string name_; public: const string& getName()const { return name_; } void setName(const string& name) { name_ = name; } int getAge() { return age_; } void setAge(int age) { age_ = age; } };
using namespace std; using namespace boost; class Person { public: Person() : personPtr_(new PersonImpl) {} ~Person() { }; private: scoped_ptrpersonPtr_; public: int getAge() { return personPtr_->getAge(); } void setAge(int age) { personPtr_->setAge(age); } const string& getName()const { return personPtr_->getName(); } void setName(const string& name) { personPtr_->setName(name); } };
using namespace std; using namespace boost; int main(int,char**) { Person person; return 0; }