了解三种C++存储方式

来源:互联网 发布:matlab取出矩阵 编辑:程序博客网 时间:2024/05/22 10:41
C++有三种存储方式:自动存储方式,静态存储方式和自由存储方式。每一种存储方式都有不同的对象初始化的方法和生存空间。在下面的段落中我们将阐述这三种存储方式的不同之处,并向大家展示怎样有效而安全地使用它们。

 

自动存储方式
 
 
通常,我们并不把局部对象定义为静态的或者外部的,而是将它定义为自动的和寄存器的。函数的自变量都是自动存储,这种存储方式被称作栈存储。下面的例子包括了多种声明对象的方式、自动存储方式的各种形式。

//s' storage type s is determined by the caller
void f(const std::string & s);

//arguments passed by value are automatic
void g(register int n);

int main()
{
 int n; // automatic because local, non-static, non-extern
 register inti;  // register implies automatic
 auto double d;  // auto implies automatic
 g(n); //passing a copy of n; the copy is automatic
 std::string s;
 f(std::string temp()); // a temp object is also automatic

自动对象通常被建立在一个函数或者一个块中,当函数或块结束时,自动对象就被立即销毁。因而,当它每次进入一个函数或块的时候,自动对象将会创建一个全新的设置,自动变量和无类对象的缺省值是不定的。
 静态存储方式 

静态存储方式
 
 
全局对象、一个类的静态数据成员和函数的静态变量都属于静态存储的范畴。一个静态对象的内存地址在整个程序运行的过程中是不变的。在一个程序的生存空间内,每个静态对象仅被构造一次。

静态数据的缺省值被初始化为二进制零,静态对象随着非无效构造函数(构造函数由编译器或者C++执行)紧接着被初始化。下面的例子展示了怎样静态存储对象。

int num; //global variables have static storage
static int sum; //so do static objects declared globally
intfunc()
{
  static int calls; //initialized to 0 by default
  return ++calls;
}

class C
{
private:
  static bool b;
};

namespace NS
{
  std::stringstr; //str has static storage

 
自由存储方式 

自由存储方式
 
 
自由存储,也被称为堆存储(在C里)或者动态存储,它包括在程序代码中使new来产生所需要的对象和变量。对象和变量将不断的分配存储空间,直到调用删除操作将它们释放。

调用删除程序失败将会引起内存不足,调用构析函数失败的结果则是无法预料的,与自动和静态的对象相比,自由存储对象的地址在运行的时候已经被确定。下面的例子展示了自动存储对象的过程。

int *p = new in  t;
char *s = new char[1024];
Shape *ps=new Triangle;
//s' storage type s is determined by the caller
void f(const std::string & s);
std::string *pstr=new std::string
f(pstr);
delete p;
delete[] s; //s is an array
delete  ps; //invokes the destructor
delete pstr; //ditto 

 
原创粉丝点击