zoukankan      html  css  js  c++  java
  • 【C++】make_shared, const与指针的关系

    、boost 和 std
    boost和std库中都有智能指针shared_ptr, make_shared.
    且std中的智能指针模块来源于boost中的智能指针。
     
    二、make_shared

    构造shared_ptr时,比new更安全、更高效的方法是make_shared(使用系统默认new操作),allocate_shared(允许用户指定allocate函数)。

    优势:new会有两次内存分配,一次是生成对象( new int() ),一次是引用计数

    make_shared把两次合并成了一次。

    boost::shared_ptr<std::string> x = boost::make_shared<std::string>("hello, world!");
    std::cout << *x; 
    // 构造一个string指针
    boost::shared_ptr<vector<int> > spv = boost::make_shared<vector<int> >(10, 2);
    // 构造一个vector指针

    二、const 与指针的关系

    2.1 裸指针与const

    2.1.1 指向常量的指针,即指针指向的内容不可以改变。有2种形式,

    const int* raw_ptr;
    int const * raw_ptr;

    此时指针可以指向任意内容。在初始化指针的时候,不需要给指针赋值

    2.1.2 常量指针,即不可以改变指针的指向。只有1种形式,

    int a = 3;
    int* const raw_ptr = &a;

    由于指针的指向不可以改变,因此在初始化时必须给常量指针赋值

    2.1.3 指向常量的常指针

    int a = 2;
    int b = 3;
    const int* const raw_ptr = &a;
    int const* const raw_ptr = &b;

    2.2 智能指针与const

    2.2.1 指向常量的智能指针

    std::shared_ptr<const T> k_s_ptr;

    2.2.2 常量智能指针

    const std::shared_ptr<T> k_s_ptr = boost::make_shared<T>();
  • 相关阅读:
    运用VS制作安装包
    return的总结
    Swift UIAlertController、UISegmentedControl
    Swift 菊花、UIPageControl和UIProgressView
    Swift UITextField各种属性的设置
    Swift 发送邮件和发短信
    Swift GCD
    swift 定义枚举和结构体 及使用
    iOS怎么来实现关闭自动锁屏
    IOS开发 清空数组正确方法
  • 原文地址:https://www.cnblogs.com/gdut-gordon/p/9426263.html
Copyright © 2011-2022 走看看