码迷,mamicode.com
首页 > 编程语言 > 详细

c++管理内存的几种方式

时间:2020-02-24 20:32:24      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:cout   何事   管理   return   out   main   ptr   自动   缺陷   

#include <iostream>
#include <memory>

static void versionOne();
static void versionTwo();

using namespace std;

int main(void) {

    versionOne();
    versionTwo();
    versionThree();
    return EXIT_SUCCESS;
}
void versionOne() {
    //c语言方式开辟内存
    int *ageC = (int*) malloc(sizeof(int));
    if(argC) {
        free(ageC);
    }
    char *c = (char*) malloc(100);
    free(c);

    //c++ 开辟内存方式
    int *age = new int(25);
    int *height = new int(160);
    //缺陷,容易忘掉free 或 delete
}

void versionTow() {
    //智能指针
    std::shared_ptr<int> age(new int(28));
    std::shared_ptr<int> height(new int(160));

    std::cout << "VersionTwo: you age is " << *age << ", and your height is "
        << *height << std::endl;
    //不需要做任何事情, 内存会自动的释放掉
    //基本上,不会造成内存泄露问题
}

c++管理内存的几种方式

标签:cout   何事   管理   return   out   main   ptr   自动   缺陷   

原文地址:https://www.cnblogs.com/lyxf/p/12358238.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!