首页 > 系统相关 >C++ 智能指针动态内存简单测试

C++ 智能指针动态内存简单测试

时间:2024-07-17 13:30:51浏览次数:8  
标签:10 arr cout sp up C++ 动态内存 test 指针

代码示例,主要来自《C++ Primer》,动态内存相关那章内容。

#include <iostream>
#include <memory>
#include <string>

namespace
{
    // 未初始化的智能指针,默认保存的空指针
    void def_null_sp_test();
    // 不是唯一用户,复制一份新的考拷贝。
    void sp_unique_copy_test();
    // weak_ptr 测试
    void wp_test();
    // 智能指针和动态数组
    void smartPtr_arr_test();
    // allocator 类测试
    void allocator_test();
}

int main()
{
    using namespace std;

    cout << "/*********def_null_sp_test()*********/" << endl;
    def_null_sp_test();
    cout << "/*********def_null_sp_test()*********/" << endl << endl;

    cout << "/*********sp_unique_copy_test()*********/" << endl;
    sp_unique_copy_test();
    cout << "/*********sp_unique_copy_test()*********/" << endl << endl;

    cout << "/*********wp_test()*********/" << endl;
    wp_test();
    cout << "/*********wp_test()*********/" << endl << endl;

    cout << "/*********smartPtr_arr_test()*********/" << endl;
    smartPtr_arr_test();
    cout << "/*********smartPtr_arr_test()*********/" << endl << endl;

    cout << "/*********allocator_test()*********/" << endl;
    allocator_test();
    cout << "/*********allocator_test()*********/" << endl << endl;

    return 0;
}

namespace
{
    void def_null_sp_test()
    {
        using namespace std;
        shared_ptr<string> p1;
        //cout << *p1 << endl; // p1 默认保存的是空指针

        if (!p1)
        {
            p1.reset(new string("hi, I'am jack."));
        }
        cout << *p1 << endl;

        *p1 = "";
        if (p1 && p1->empty())
        {
            *p1 = "hello world!";
        }
        cout << *p1 << endl;
    }

    void sp_unique_copy_test()
    {
        using namespace std;
        shared_ptr<string> p1(new string("hello world!"));
        shared_ptr<string> p2 = p1;
        shared_ptr<string> p3 = p2;
        cout << "p1 对象的引用次数,use_count = " << p1.use_count() << endl;

        cout << "p3 = " << *p3 << endl;
        if (!p3.unique())
        {
            p3.reset(new string(*p3));
        }
        *p3 += " good morning.";
        cout << "p3 新内容是:" << *p3 << endl;
        cout << "p1 对象的引用次数,use_count = " << p1.use_count() << endl;
        cout << "p1 的内容是:" << *p1 << endl;
    }

    void wp_test()
    {
        using namespace std;
        auto sp = make_shared<int>(100);
        weak_ptr<int> wp(sp);
        cout << "sp 的引用次数 use_count = " << sp.use_count() << endl;;
        auto ret = wp.lock();
        if (!ret)
        {
            cout << "对象已经被释放!" << endl;
        }
        else
        {
            cout << "sp 的引用次数 use_count = " << sp.use_count() << endl;
        }
    }

    void smartPtr_arr_test()
    {
        using namespace std;
        unique_ptr<int[]> up_arr(new int[10]); // 释放时自己会调用 delete[], 人肉经常会忘记[]
        for (size_t i = 0; i != 10; ++i)
        {// 赋值
            up_arr[i] = i * 10;
        }
        for (size_t i = 0; i != 10; ++i)
        {// 显示
            cout << "up_arr[i] = " << up_arr[i] << " ";
        }
        cout << endl;

        // 如果用 shared_ptr 管理动态数组,需要自定义删除器,记得带[]
        shared_ptr<int> sp_arr(new int[10], [](int* p) {delete[] p; });
        // 遍历只能这样
        for (size_t i = 0; i != 10; ++i)
        {
            *(sp_arr.get() + i) = i * 10;
        }
        for (size_t i = 0; i != 10; ++i)
        {
            cout << "sp_arr[i] = " << *(sp_arr.get() + i) << " ";
        }
        cout << endl;
    }

    void allocator_test()
    {
        using namespace std;
        const size_t ALLOC_SIZE = 3;

        allocator<string> allco_strs;
        auto const p = allco_strs.allocate(ALLOC_SIZE); // 分配n个未初始化的string

        auto q = p;
        allco_strs.construct(q++); // 空字符串
        allco_strs.construct(q++, 5, 'c');
        allco_strs.construct(q++, "hello world");

        cout << *p << endl;

        cout << "allocator 遍历:" << endl;
        while (q != p)
        {
            auto temp = --q;
            cout << *temp << endl;
            allco_strs.destroy(temp); // 析构
        }

        allco_strs.deallocate(p, ALLOC_SIZE); // 释放,归还系统
    }
}

输出:

/*********def_null_sp_test()*********/
hi, I'am jack.
hello world!
/*********def_null_sp_test()*********/

/*********sp_unique_copy_test()*********/
p1 对象的引用次数,use_count = 3
p3 = hello world!
p3 新内容是:hello world! good morning.
p1 对象的引用次数,use_count = 2
p1 的内容是:hello world!
/*********sp_unique_copy_test()*********/

/*********wp_test()*********/
sp 的引用次数 use_count = 1
sp 的引用次数 use_count = 2
/*********wp_test()*********/

/*********smartPtr_arr_test()*********/
up_arr[i] = 0 up_arr[i] = 10 up_arr[i] = 20 up_arr[i] = 30 up_arr[i] = 40 up_arr[i] = 50 up_arr[i] = 60 up_arr[i] = 70 up_arr[i] = 80 up_arr[i] = 90
sp_arr[i] = 0 sp_arr[i] = 10 sp_arr[i] = 20 sp_arr[i] = 30 sp_arr[i] = 40 sp_arr[i] = 50 sp_arr[i] = 60 sp_arr[i] = 70 sp_arr[i] = 80 sp_arr[i] = 90
/*********smartPtr_arr_test()*********/

/*********allocator_test()*********/

allocator 遍历:
hello world
ccccc

/*********allocator_test()*********/

按任意键关闭此窗口. . .

标签:10,arr,cout,sp,up,C++,动态内存,test,指针
From: https://www.cnblogs.com/huvjie/p/18307110

相关文章

  • XX2104 培训【C++解决】
    描述某培训机构的学员有如下信息:姓名(字符串)年龄(周岁,整数)去年NOIP成绩(整数,且保证是5的倍数)经过为期一年的培训,所有同学的成绩都有所提高,提升了20%(当然NOIP满分是600分,不能超过这个得分)。输入学员信息,请设计一个结构体储存这些学生信息,并设计一个函数模拟培训......
  • C++第七弹 -- C/C++内存管理
    目录前言一.C/C++内存分布二.C语言中动态内存管理方式三.C++中动态内存管理四.operatornew与operatordelete函数五.new和delete的实现原理1.内置类型2.自定义类型六.定位new表达式(placement-new)七.常见面试题总结前言在C/C++编程中,内存管理是至关重要的......
  • C++(回调函数)
    目录1.使用函数指针2.使用函数对象(仿函数)3.使用std::function和std::bind4.小结回调函数是一种允许函数作为参数传递给另一个函数的机制。在C++中,回调函数常用于实现事件驱动编程、异步操作和可重用性等功能。C++中有多种实现回调函数的方法,包括使用函数指针、函数对象(仿函......
  • c++ Program to print pyramid pattern (打印金字塔图案的程序)
    编写程序打印由星星组成的金字塔图案 例子: 输入:n=6输出:    *    **    ***    ****    *****    ******     *****    ****    ***    **     *......
  • C/C++ 位运算注意事项
    在C/C++中使用位运算时,需要注意多个方面以确保代码的正确性和效率。以下是一些关键的注意事项:1.操作数类型整型数据:位运算符(如&、|、^、~、<<、>>)只能用于整型数据,包括带符号或无符号的char、short、int、long等类型。尝试对非整型数据(如float、double)进行位运算会导致编......
  • 归并排序--C++
        归并排序是建立在归并操作上的一种有效,稳定的排序算法,该算法是采“分而自治”用的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。​图片来源于网络核心代码:voidabc(intx[],intq,intp){if(q>=p)r......
  • C++ 多态:探索对象的动态行为
    C++多态:探索对象的动态行为在C++中,多态性是一种强大的特性,它允许我们通过基类指针或引用来调用派生类的方法。多态性不仅增加了程序的灵活性,还使得代码更加易于扩展和维护。本文将深入探讨C++中的多态性,包括静态多态(主要通过函数重载和模板实现)和动态多态(主要通过虚函数......
  • C++ 数据抽象:构建高效、可维护的代码基石
    C++数据抽象:构建高效、可维护的代码基石在软件开发中,数据抽象是一个核心概念,它允许我们隐藏实现细节,仅通过公共接口与外部世界交互。这种封装机制不仅提高了代码的安全性,还促进了代码的复用和可维护性。C++作为一门强大的面向对象编程语言,通过类(Classes)和接口(Interfaces,尽......
  • C++ 重载运算符与重载函数:深入解析与实例
    引言在C++中,重载(Overloading)是一个强大的特性,它允许我们为函数或运算符提供多个定义,这些定义之间通过参数的数量、类型或顺序来区分。重载运算符和重载函数是C++面向对象编程中常见的实践,它们不仅增强了代码的可读性和易用性,还使得类能够模拟内置数据类型的行为。本文将深......
  • 2024年华为OD机试真题-符号运算-(C++/Java/python)-OD统一考试(C卷D卷)
      2024华为OD机试真题目录-(B卷C卷D卷)-【C++JavaPython】    题目描述给定一个表达式,求其分数计算结果。表达式的限制如下:所有的输入数字皆为正整数(包括0)仅支持四则运算(+-*,/)和括号结果为整数或分数,分数必须化为最简格式(比如6,3/4,7/8,90/7)除数可能为0,如果遇到......