设为首页 加入收藏

TOP

C++中new和delete的几点说明
2013-11-20 14:24:33 来源: 作者: 【 】 浏览:188
Tags:new delete 说明

  用途:动态分配和撤销内存空间,和C语言中的malloc和free的作用一样,区别在于new和delete的效率更高。

  注意:new和delete不是函数,而是C++提供的运算符,和加减乘除运算符一样。

  使用:new 类型 [初值],如 new int  [100];

  delete    指针变量    (对变量)

  delete   [ ] 指针变量  (对数组)

  执行结果:new  返回一个指针,如未能成功分配内存,则返回NULL;delete删除指针指向的空间。

  例子:

  #include<iostream>

  #include<string>

  using namespace std;

  struct Student

  {

  string name;

  int id;

  char sex;

  };

  int main()

  {

  Student *p;

  p=new Student;

  p->name="Wang Fang";

  p->id=216016;

  p->sex='f';

  cout<<p->name<<endl;

  cout<<p->id<<endl;

  cout<<p->sex<<endl;

  delete p;

  system("pause");

  return 0;

  }

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++各个容器比较 下一篇C++和MATLAB混合编程

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Libevent C++ 高并发 (2025-12-26 00:49:30)
·C++ dll 设计接口时 (2025-12-26 00:49:28)
·透彻理解 C 语言指针 (2025-12-26 00:22:52)
·C语言指针详解 (经典 (2025-12-26 00:22:49)
·C 指针 | 菜鸟教程 (2025-12-26 00:22:46)