【cmu15445c++入门】(5)C++ 包装类(管理资源的类)

2024-02-01 22:52

本文主要是介绍【cmu15445c++入门】(5)C++ 包装类(管理资源的类),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、背景

c++包装类

二、运行代码 


// A C++ wrapper class is a class that manages a resource. A resource
// could be memory, file sockets, or a network connection. Wrapper classes
// often use the RAII (Resource Acquisition is Initialization) C++ 
// programming technique. Using this technique implies that the resource's
// lifetime is tied to its scope. When an instance of the wrapper class is
// constructed, this means that the underlying resource it is managing is
// available, and when this instance is destructed, the resource also
// is unavailable. //C++ 包装类是管理资源的类。资源可以是内存、文件套接字或网络连接。
//包装类通常使用 RAII(资源获取即初始化)C++ 编程技术。
//使用此技术意味着资源的生存期与其范围相关联。
//当构造包装类的实例时,这意味着它所管理的基础资源是可用的,而当此实例被销毁时,该资源也是不可用的。// Here are a couple resources on RAII that are useful:
// https://en.cppreference.com/w/cpp/language/raii (RAII docs on the CPP
// docs website)
// Interesting Stack Overflow answers to "What is meant by RAII?":
// https://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii// In this file, we will look at a basic implementation of a wrapper class that
// manages an int*. We will also look at usage of this class.// Includes std::cout (printing) for demo purposes.
#include <iostream>
// Includes the utility header for std::move.
#include <utility>// The IntPtrManager class is a wrapper class that manages an int*. The
// resource that this class is managing is the dynamic memory accessible via
// the pointer ptr_. By the principles of the RAII technique, a wrapper class
// object should not be copyable, since one object is supposed to manage one
// resource. Therefore, the copy assignment operator and copy constructor are
// deleted from this class. However, the class is still moveable from different
// lvalues/owners, and has a move constructor and move assignment operator.
// Another reason that wrapper classes forbid copying is because they destroy
// their resource in the destructor, and if two objects are managing the same
// resource, there is a risk of double deletion of the resource.
// IntPtrManager 类是管理 int* 的包装类。此类管理的资源是通过指针ptr_访问的动态内存。
// 根据 RAII 技术的原则,包装类对象不应该是可复制的,因为一个对象应该管理一个资源。
// 因此,从此类中删除复制赋值运算符和复制构造函数。但是,该类仍然可以从不同的左值/所有者移动,并且具有移动构造函数和移动赋值运算符。
// 包装类禁止复制的另一个原因是在析构函数中进行做资源销毁,如果两个对象管理同一资源,则存在双重删除资源的风险。class IntPtrManager {public:// All constructors of a wrapper class are supposed to initialize a resource.// In this case, this means allocating the memory that we are managing.// The default value of this pointer's data is 0.IntPtrManager() {ptr_ = new int;*ptr_ = 0;}// Another constructor for this wrapper class that takes a initial value.IntPtrManager(int val) {ptr_ = new int;*ptr_ = val;}// Destructor for the wrapper class. The destructor must destroy the// resource that it is managing; in this case, the destructor deletes// the pointer!~IntPtrManager() {// Note that since the move constructor marks objects invalid by setting// their ptr_ value to nullptr, we have to account for this in the // destructor. We don't want to be calling delete on a nullptr!std::cout << "~IntPtrManager()" << std::endl;if (ptr_) {std::cout << "ptr is  " << ptr_ <<std::endl;delete ptr_;}}// Move constructor for this wrapper class. Note that after the move// constructor is called, effectively moving all of other's data into// the specified instance being constructed, the other object is no// longer a valid instance of the IntPtrManager class, since it has// no memory to manage. IntPtrManager(IntPtrManager&& other) {ptr_ = other.ptr_;other.ptr_ = nullptr;}// Move assignment operator for class Person. Similar techniques as// the move constructor.IntPtrManager &operator=(IntPtrManager &&other) {ptr_ = other.ptr_;other.ptr_ = nullptr;return *this;}// We delete the copy constructor and the copy assignment operator,// so this class cannot be copy-constructed. IntPtrManager(const IntPtrManager &) = delete;IntPtrManager &operator=(const IntPtrManager &) = delete;// Setter function.void SetVal(int val) {*ptr_ = val;}// Getter function.int GetVal() const {return *ptr_;}private:int *ptr_;};int main() {// We initialize an instance of IntPtrManager. After it is initialized, this// class is managing an int pointer.IntPtrManager a(445);// Getting the value works as expected.std::cout << "1. Value of a is " << a.GetVal() << std::endl;// Setting the value goes through, and the value can retrieved as expected.a.SetVal(645);std::cout << "2. Value of a is " << a.GetVal() << std::endl;// Now, we move the instance of this class from the a lvalue to the b lvalue// via the move constructor.IntPtrManager b(std::move(a));// Retrieving the value of b works as expected because b is now managing the// data originally constructed by the constructor that created a. Note that// calling GetVal() on a will segfault, and a is supposed to effectively be// empty and unusable in this state.std::cout << "Value of b is " << b.GetVal() << std::endl;// 此时去访问a必然会报错退出//std::cout << "Value of a is " << a.GetVal() << std::endl;IntPtrManager c = std::move(b);std::cout << "Value of c is " << c.GetVal() << std::endl;c.SetVal(123);// Once this function ends, the destructor for both a and b will be called.// a's destructor will note that the ptr_ it is managing has been set to // nullptr, and will do nothing, while b's destructor should free the memory// it is managing.// 在函数退出之后,会有析构函数return 0;
}

三、运行结果

这篇关于【cmu15445c++入门】(5)C++ 包装类(管理资源的类)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/668732

相关文章

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

【C++ Primer Plus习题】13.4

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream>#include "port.h"int main() {Port p1;Port p2("Abc", "Bcc", 30);std::cout <<

C++包装器

包装器 在 C++ 中,“包装器”通常指的是一种设计模式或编程技巧,用于封装其他代码或对象,使其更易于使用、管理或扩展。包装器的概念在编程中非常普遍,可以用于函数、类、库等多个方面。下面是几个常见的 “包装器” 类型: 1. 函数包装器 函数包装器用于封装一个或多个函数,使其接口更统一或更便于调用。例如,std::function 是一个通用的函数包装器,它可以存储任意可调用对象(函数、函数

综合安防管理平台LntonAIServer视频监控汇聚抖动检测算法优势

LntonAIServer视频质量诊断功能中的抖动检测是一个专门针对视频稳定性进行分析的功能。抖动通常是指视频帧之间的不必要运动,这种运动可能是由于摄像机的移动、传输中的错误或编解码问题导致的。抖动检测对于确保视频内容的平滑性和观看体验至关重要。 优势 1. 提高图像质量 - 清晰度提升:减少抖动,提高图像的清晰度和细节表现力,使得监控画面更加真实可信。 - 细节增强:在低光条件下,抖

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

06 C++Lambda表达式

lambda表达式的定义 没有显式模版形参的lambda表达式 [捕获] 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 有显式模版形参的lambda表达式 [捕获] <模版形参> 模版约束 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 含义 捕获:包含零个或者多个捕获符的逗号分隔列表 模板形参:用于泛型lambda提供个模板形参的名

数论入门整理(updating)

一、gcd lcm 基础中的基础,一般用来处理计算第一步什么的,分数化简之类。 LL gcd(LL a, LL b) { return b ? gcd(b, a % b) : a; } <pre name="code" class="cpp">LL lcm(LL a, LL b){LL c = gcd(a, b);return a / c * b;} 例题:

软考系统规划与管理师考试证书含金量高吗?

2024年软考系统规划与管理师考试报名时间节点: 报名时间:2024年上半年软考将于3月中旬陆续开始报名 考试时间:上半年5月25日到28日,下半年11月9日到12日 分数线:所有科目成绩均须达到45分以上(包括45分)方可通过考试 成绩查询:可在“中国计算机技术职业资格网”上查询软考成绩 出成绩时间:预计在11月左右 证书领取时间:一般在考试成绩公布后3~4个月,各地领取时间有所不同

安全管理体系化的智慧油站开源了。

AI视频监控平台简介 AI视频监控平台是一款功能强大且简单易用的实时算法视频监控系统。它的愿景是最底层打通各大芯片厂商相互间的壁垒,省去繁琐重复的适配流程,实现芯片、算法、应用的全流程组合,从而大大减少企业级应用约95%的开发成本。用户只需在界面上进行简单的操作,就可以实现全视频的接入及布控。摄像头管理模块用于多种终端设备、智能设备的接入及管理。平台支持包括摄像头等终端感知设备接入,为整个平台提