您的位置:首页 > 编程语言 > C语言/C++

The Leak of The Memory In C++ 1.1

2014-04-24 09:03 417 查看
Recent days I want to write some articles to summarise the knowledge

of C++ which I learned and practice my English. So...

The Leak of The Memory in C++ (chapter 1.1)

So many people asked me something about the leak of the memory. They

said that in C++ you must be careful when use pointer. I must say they were

right before STL published.

In C++, we have so many methods to avoid to using pointer, why people

always convince developers to use pointer. In this article, I'll try to convince

regular developers to give raw pointer up and to forget it in your development.

First, I want to show you the easest way to avoid using pointer which

is smart pointer in STL (if you don't know what is STL, I recommand you read a

book which name is "C++ Primer").

In C++, smart pointer is a way to convince people to give raw pointer

up. smart pointer is a C++ class which encapsulates a raw pointer and which

can release the raw pointer when pointer leaves its scope. In C++98, which

provides just one smart pointer for developer, But so many people provide so

many another kinds of smart pointer in boost, Loki etc.

Before I introduce the way to use smart pointers, I'll introduce a

class to you, even this class alread introduced in lots of books, and I will

use this class in demos.

the source code in Person.h

#ifndef __PERSON__H
#define __PERSON__H

#include <string>

using namespace std;

class Person
{
int age_;
string name_;

public:
Person()
: age_(0)
{}

~Person()
{
cout << "I'm destructed" << endl;
};

public:
int getAge()
{
return age_;
}

void setAge(int age)
{
age_ = age;
}

const string& getName()const
{
return name_;
}

void setName(const string& name)
{
name_ = name;
}
};
#endif//__PERSON__H


The auto_ptr, the first smart pointer I'll introduce to you. As a

first smart pointer appeared in STL, it is a miracle for me, because this one

I found a way to avoid using raw pointer, I found that what is Encapsulation

and what is Templement. The code is below:

#include <iostream>
#include <memory>
#include "Person.h"

using namespace std;

int main(int, char**)
{
auto_ptr<Person> p1(new Person);
auto_ptr<Person> p2(new Person);
auto_ptr<Person> p3(new Person);
return 0;
}


If you execute code, you will find that every object's destructors are

called, so you can use auto_ptr in your functions, classes without consideration

of loss of performence.

You already know benifit of the auto_ptr, but you must be careful its side effect.

1. you can't assign an auto_ptr to another anto_ptr, if you did, just

like this:

auto_ptr<Person> p1(new Person);

auto_ptr<Person> p2 = p1;

you would find that p1 is empty now.

2. you can't put an auto_ptr in vector or another containers, I

think I have unnecessary to warry about this, because compiler will prevent you do

that.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: