当前位置: 首页 > news >正文

智能指针

智能指针

  • 智能指针
    • stdauto_ptr
    • boostscoped_ptr
    • boostshared_ptr
    • boostscoped_array
    • boostshared_array
    • boostweak_ptr
    • boostinstrusive_ptr
    • 后记

std::auto_ptr


使用总结
1.(deprecated since C++11) (until C++17) 1
2.尽量不要使用”=”. 如果使用了, 请不要再使用先前对象.
3.记住release(0)函数不会释放对象, 仅仅归还所有权, release(0)返回T*类型.
4.由于std::auto_ptr的”operator=”问题, 由其管理的对象不能放入 std::vector 等容器中. 同样的道理, std::auto_ptr最好不要当成参数传递.
示例代码
#include "simple.h"

#include <memory>

int main() {
        std::auto_ptr<Simple> my_memory(new Simple(1));   // 创建对象,输出:Simple1
        if (my_memory.get()) {                            // 判断智能指针是否为空
                my_memory->PrintSomething();                    // 使用 operator-> 调用智能指针对象中的函数
                my_memory.get()->info_extend = "Addition";      // 使用 get() 返回裸指针,然后给内部对象赋值
                my_memory->PrintSomething();                    // 再次打印,表明上述赋值成功
                (*my_memory).info_extend += " other";           // 使用 operator* 返回智能指针内部对象,然后用“.”调用智能指针对象中的
函数
                my_memory->PrintSomething();                    // 再次打印,表明上述赋值成功
          }

        std::auto_ptr<Simple> instance(new Simple(1));
        if(instance.get()){
                std::auto_ptr<Simple> instance2;
                instance2 = instance; //导致instance悬空;
                instance2->PrintSomething();
                //instance->PrintSomething(); //崩溃;
                //instance2->release(); //并未释放内存, 只交出使用权; release返回Simple*;
                //instance2->reset(); //释放内存; reset(1)已经被启用;
                //delete instance2->release(); 也可释放内存; 但是release(0)已经被弃用;
        }

boost::scoped_ptr


总结
1.独享内存. 即不能被赋值给另一个同类scoped_ptr指针.
2.因为具有1所描述的特性, 避免了std::auto_ptr的几个问题. 比如赋值会编译错误;
3.没有release(0), 可以通过reset(1)释放内存.

代码
:

#include "simple.h"

#include <boost/smart_ptr.hpp>

int main() {
        boost::scoped_ptr<Simple> my_memory(new Simple(1));   // 创建对象,输出:Simple1
        if (my_memory.get()) {                            // 判断智能指针是否为空
                my_memory->PrintSomething();                    // 使用 operator-> 调用智能指针对象中的函数
                my_memory.get()->info_extend = "Addition";      // 使用 get() 返回裸指针,然后给内部对象赋值
                my_memory->PrintSomething();                    // 再次打印,表明上述赋值成功
                (*my_memory).info_extend += " other";           // 使用 operator* 返回智能指针内部对象,然后用“.”调用智能指针对象中的函数
                my_memory->PrintSomething();                    // 再次打印,表明上述赋值成功
          }

        boost::scoped_ptr<Simple> instance(new Simple(1));
        if(instance.get()){
                boost::scoped_ptr<Simple> instance2;
                //instance2 = instance; //err, forbidden by compiler;
                //instance->release(); //err, has no such member function;
        }

          return 0;
}

boost::shared_ptr


总结
1.共享内存, 具有operator=操作, 带引用计数.
代码
#include "simple.h"

#include <boost/smart_ptr.hpp>

void TestSharedPtr(boost::shared_ptr<Simple> memory) {  // 注意:无需使用 reference (或 const reference)

  memory->PrintSomething();

  std::cout << "TestSharedPtr UseCount: " << memory.use_count() << std::endl;

}

int main() {
        boost::shared_ptr<Simple> my_memory(new Simple(1));   // 创建对象,输出:Simple:1
        if (my_memory.get()) {                            // 判断智能指针是否为空
                my_memory->PrintSomething();                    // 使用 operator-> 调用智能指针对象中的函数
                my_memory.get()->info_extend = "Addition";      // 使用 get() 返回裸指针,然后给内部对象赋值
                my_memory->PrintSomething();                    // 再次打印,表明上述赋值成功
                (*my_memory).info_extend += " other";           // 使用 operator* 返回智能指针内部对象,然后用“.”调用智能指针对象中的函数
                my_memory->PrintSomething();                    // 再次打印,表明上述赋值成功
          }

         std::cout << "TestSharedPtr2 UseCount: " << my_memory.use_count() << std::endl;

         TestSharedPtr(my_memory);

        std::cout << "TestSharedPtr2 UseCount: " << my_memory.use_count() << std::endl;



  //my_memory.release();// 编译 error: 同样,shared_ptr 也没有 release 函数

          return 0;
}

boost::scoped_array


scoped_ptr的数组版
代码 :
#include "simple.h"

#include <boost/smart_ptr.hpp>

int main(){
        boost::scoped_array<Simple> test_array(new Simple[2]);
        if(test_array.get()){
                test_array[0].PrintSomething();

                test_array.get()[0].info_extend = "Addition";
                test_array[0].PrintSomething();
                //(*test_array)[0].info_extend += "other"; //err, scoped_array has no *;
                //test_array[0].release(); //test_array[0] is a Simple;
                boost::scoped_array<Simple> test_array2;
                //test_array2=test_array; //err scoped_array has no operator=;
        }
}

boost::shared_array


shared_ptr的数组版
代码
#include "simple.h"

#include <boost/smart_ptr.hpp>

void test_shared_array(boost::shared_array<Simple> memory){ // no need to be reference or const reference;
        std::cout << "Test shared array use count:" << memory.use_count() << std::endl;
}

int main(){
        boost::shared_array<Simple> test_array(new Simple[2]);
        if(test_array.get()){
                test_array[0].PrintSomething();

                test_array.get()[0].info_extend = "Addition";
                test_array[0].PrintSomething();
                //(*test_array)[0].info_extend += "other"; //err, shared_array has no *;
                //test_array[0].release(); //test_array[0] is a Simple;
                boost::shared_array<Simple> test_array2;
                test_array2=test_array;
                std::cout << "Test shared array use count:" << test_array.use_count() << std::endl;
        }

        std::cout << "Test shared array use count:" << test_array.use_count() << std::endl;
        test_shared_array(test_array);
        std::cout << "Test shared array use count:" << test_array.use_count() << std::endl;
}

boost::weak_ptr


boost::instrusive_ptr


后记


目前这些都只是常识, 关于智能指针还有很多需要注意的地方, 和很多可以巧妙运用的地方. 限于现在水平有限, 后面再补充.

重要参考博文:2

相关文章:

  • 常用开发工具快捷键--Visual Studio 2010+Visual C++ 6.0
  • Qt Creator 常用快捷键
  • C++ 运算符优先级表
  • Snailevil's Qt List
  • Snailevil's C List
  • Snailevil's C++ List
  • Snailevil's To Do List
  • 吃一堑,长一智---Qt
  • 常见颜色关键字
  • 博客模板
  • JAVA 中的类和对象(1)
  • Java语言基础2
  • Java语言基础1
  • C语言运算符表达式
  • C语言基本数据类型
  • JS中 map, filter, some, every, forEach, for in, for of 用法总结
  • C++类的相互关联
  • CSS居中完全指南——构建CSS居中决策树
  • CSS相对定位
  • Java 内存分配及垃圾回收机制初探
  • magento 货币换算
  • MaxCompute访问TableStore(OTS) 数据
  • Node + FFmpeg 实现Canvas动画导出视频
  • RxJS: 简单入门
  • Storybook 5.0正式发布:有史以来变化最大的版本\n
  • Vue2 SSR 的优化之旅
  • 大型网站性能监测、分析与优化常见问题QA
  • 跨域
  • 浅析微信支付:申请退款、退款回调接口、查询退款
  • 实战|智能家居行业移动应用性能分析
  • 使用 Xcode 的 Target 区分开发和生产环境
  • 数组的操作
  • 小程序 setData 学问多
  • 做一名精致的JavaScripter 01:JavaScript简介
  • 阿里云ACE认证之理解CDN技术
  • # Swust 12th acm 邀请赛# [ E ] 01 String [题解]
  • #我与Java虚拟机的故事#连载18:JAVA成长之路
  • (¥1011)-(一千零一拾一元整)输出
  • (1)(1.13) SiK无线电高级配置(六)
  • (HAL)STM32F103C6T8——软件模拟I2C驱动0.96寸OLED屏幕
  • (zt)最盛行的警世狂言(爆笑)
  • (附源码)计算机毕业设计SSM疫情社区管理系统
  • (免费领源码)Java#Springboot#mysql农产品销售管理系统47627-计算机毕业设计项目选题推荐
  • (一)基于IDEA的JAVA基础12
  • (原創) 如何動態建立二維陣列(多維陣列)? (.NET) (C#)
  • *(长期更新)软考网络工程师学习笔记——Section 22 无线局域网
  • .NET 6 在已知拓扑路径的情况下使用 Dijkstra,A*算法搜索最短路径
  • .NET Core使用NPOI导出复杂,美观的Excel详解
  • .net mvc 获取url中controller和action
  • .NET MVC之AOP
  • .NET Reactor简单使用教程
  • .Net Remoting(分离服务程序实现) - Part.3
  • .NET 分布式技术比较
  • .net 托管代码与非托管代码
  • .NET处理HTTP请求