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

#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;
    //不需要做任何事情, 内存会自动的释放掉
    //基本上,不会造成内存泄露问题
}

原文链接: https://www.cnblogs.com/lyxf/p/12358238.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/331531

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午6:05
下一篇 2023年3月1日 下午6:05

相关推荐