博客
关于我
C++ 动态内存分配基础
阅读量:242 次
发布时间:2019-03-01

本文共 868 字,大约阅读时间需要 2 分钟。

新加入的内容主要围绕C++语言中的动态内存管理展开,以下是具体内容:

动态申请空间

在C++程序中,动态内存管理允许开发者根据需要灵活分配和释放内存资源。通过使用new操作符,可以向程序中申请内存空间,以支持对象的创建或数据结构的动态扩展。以下是几种常见的动态申请方式及其示例:

  • 单个对象的动态申请

    使用new操作符可以为一个特定对象分配内存:

    int *p = new int(200);

    这段代码申请了一个整数对象的内存空间,并将其存储在指针p中。随后可以使用delete操作符释放该内存:

    delete p;
  • 字符串对象的动态申请

    对于字符串对象,可以使用new操作符分配特定长度的内存:

    string *ps = new string("purple paplace");

    申请完成后,可以通过delete操作符释放字符串对象的内存:

    delete ps;
  • 结构体对象的动态申请

    结构体也是可以通过new操作符动态申请内存的:

    struct Stu {      int age;      string name;  };  Stu *pStu = new Stu{10, "bob"};

    申请完成后,使用delete操作符释放该指针所指的内存:

    delete pStu;
  • 数组的动态申请

    使用new[]操作符可以申请数组的内存。例如,申请一个大小为5的整数数组:

    int *pi = new int[5];

    使用delete[]操作符释放该数组:

    delete[] pi;
  • 多维数组的动态申请

    对于多维数组,可以使用嵌套的new[]操作符分配内存。例如,申请一个大小为2、3、4的三维数组:

    int(*pa)[3][4][5] = new int[2][3][4][5];

    使用delete[]操作符释放该数组:

    delete[] pa;
  • 需要注意的是,动态申请内存后必须及时释放,以避免内存泄漏。C++提供了deletedelete[]操作符,以及智能指针(unique_ptrshared_ptr等)来简化内存管理。

    转载地址:http://xmhv.baihongyu.com/

    你可能感兴趣的文章
    SSM(Spring+SpringMvc+Mybatis)整合开发笔记
    查看>>
    ViewHolder的改进写法
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    sql查询中 查询字段数据类型 int 与 String 出现问题
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.http.conn.HttpHostConnectException: Connection to refused
    查看>>
    org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:processDebugManifest'
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    org.springframework.amqp.AmqpConnectException:java.net.ConnectException:Connection timed out:connect
    查看>>