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

[C++学习笔记]动态内存管理

2010-03-25 18:50 316 查看
1.静态内存和动态内存

      静态内存缺点:需为变量分配尽可能大的内存,此变量并一直占用内存

      动态内存由一些没有名字、只有地址的内存块构成,内存块是在程序运行期间动态分配的。new语句将返回新分配地址块的起始地址。通常需把这个地址保存到一个指针变量里以便今后使用。

      int *i = new int;

      若没有足够可用空间,new语句抛出std::bad_alloc异常,导致程序结束执行。

      在用完内存块之后,应用delete语句把它还给内存池。作为一种附加保险措施,释放内存块后应把与之关联的指针设置为NULL

      delete i;

      i = NULL;

      把某指针设为NULL的目的是为了让程序明确知道这个指针已不再指向一个内存块,消除对指针引用失败而留下的一些隐患。

      最重要的是new与delete要匹配。

 

2.为对象分配内存

      new向内存池申请内存,delete释放内存。

      动态创建对象时,如果那个类的构造器有输入参数,那么就把它们放在类名后的括号里传递过去,这与创建静态对象的做法完全一样

      Company *company = new Company("IBM");

      在操作时,必须使用指针成员操作符。该语法与struct相同,需使用->操作符:

      company -> printInfo();

 

      delete company;

      company = NULL;

 

3.动态数组:为长度可变的数组分配内存

   
#include <iostream>
#include <string>
int main()
{
unsigned int count = 0;
std::cout<<"Number of elements to allocate?";
std::cin>>count;
int *x= new int[count];
for (int i=0;i<count;i++)
{
x[i]=count-i;
}

for (i=0;i<count;i++)
{
std::cout<<"The value of x["<<i<<"] is "<<x[i]<<"/n";
}
//Free the memory
//must use delete[] not delete.
delete[] x;
x=NULL;
std::cin.ignore(100,'/n');
std::cout<<"Please Enter or Return to continue.";
std::cin.get();
return 0;
}


 

4.从函数或方法返回内存

      让函数返回一个指向内存块的指针。

#include <iostream>
#include <string>
class Company
{
public:
Company(std::string name);
virtual void printInfo();
protected:
std::string name;
private:
};
class Publisher:public Company
{
public:
Publisher(std::string name,int booksPublished);
virtual void printInfo();
protected:
private:
int booksPublished;
};
Company::Company(std::string name)
{
this->name = name;
}
void Company::printInfo()
{
std::cout<<"This is a company called '"<<name<<"'./n";
}
Publisher::Publisher(std::string name,int booksPublished):Company(name)
{
this->booksPublished = booksPublished;
}
void Publisher::printInfo()
{
std::cout<<"This is a publisher called '"<<name<<"' that has published "<<booksPublished<<" books./n";
}
Company *createCompany(std::string name,int booksPublished = -1);
int main()
{
Company *company = createCompany("IBM");
company->printInfo();
delete company;
company = NULL;
company = createCompany("Peachpit",99999);
company->printInfo();
delete company;
company = NULL;
std::cout<<"Press Enter or Return to continue.";
std::cin.get();
return 0;
}
Company *createCompany(std::string name,int booksPublished /* = -1 */)
{
if (booksPublished<0)
{
return new Company(name);
}
else{
return new Publisher(name,booksPublished);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ delete string null ibm struct