【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

相关文章

C++中使用vector存储并遍历数据的基本步骤

《C++中使用vector存储并遍历数据的基本步骤》C++标准模板库(STL)提供了多种容器类型,包括顺序容器、关联容器、无序关联容器和容器适配器,每种容器都有其特定的用途和特性,:本文主要介绍C... 目录(1)容器及简要描述‌php顺序容器‌‌关联容器‌‌无序关联容器‌(基于哈希表):‌容器适配器‌:(

高效管理你的Linux系统: Debian操作系统常用命令指南

《高效管理你的Linux系统:Debian操作系统常用命令指南》在Debian操作系统中,了解和掌握常用命令对于提高工作效率和系统管理至关重要,本文将详细介绍Debian的常用命令,帮助读者更好地使... Debian是一个流行的linux发行版,它以其稳定性、强大的软件包管理和丰富的社区资源而闻名。在使用

C++中实现调试日志输出

《C++中实现调试日志输出》在C++编程中,调试日志对于定位问题和优化代码至关重要,本文将介绍几种常用的调试日志输出方法,并教你如何在日志中添加时间戳,希望对大家有所帮助... 目录1. 使用 #ifdef _DEBUG 宏2. 加入时间戳:精确到毫秒3.Windows 和 MFC 中的调试日志方法MFC

python使用watchdog实现文件资源监控

《python使用watchdog实现文件资源监控》watchdog支持跨平台文件资源监控,可以检测指定文件夹下文件及文件夹变动,下面我们来看看Python如何使用watchdog实现文件资源监控吧... python文件监控库watchdogs简介随着Python在各种应用领域中的广泛使用,其生态环境也

深入理解C++ 空类大小

《深入理解C++空类大小》本文主要介绍了C++空类大小,规定空类大小为1字节,主要是为了保证对象的唯一性和可区分性,满足数组元素地址连续的要求,下面就来了解一下... 目录1. 保证对象的唯一性和可区分性2. 满足数组元素地址连续的要求3. 与C++的对象模型和内存管理机制相适配查看类对象内存在C++中,规

SpringBoot使用minio进行文件管理的流程步骤

《SpringBoot使用minio进行文件管理的流程步骤》MinIO是一个高性能的对象存储系统,兼容AmazonS3API,该软件设计用于处理非结构化数据,如图片、视频、日志文件以及备份数据等,本文... 目录一、拉取minio镜像二、创建配置文件和上传文件的目录三、启动容器四、浏览器登录 minio五、

在 VSCode 中配置 C++ 开发环境的详细教程

《在VSCode中配置C++开发环境的详细教程》本文详细介绍了如何在VisualStudioCode(VSCode)中配置C++开发环境,包括安装必要的工具、配置编译器、设置调试环境等步骤,通... 目录如何在 VSCode 中配置 C++ 开发环境:详细教程1. 什么是 VSCode?2. 安装 VSCo

IDEA中的Kafka管理神器详解

《IDEA中的Kafka管理神器详解》这款基于IDEA插件实现的Kafka管理工具,能够在本地IDE环境中直接运行,简化了设置流程,为开发者提供了更加紧密集成、高效且直观的Kafka操作体验... 目录免安装:IDEA中的Kafka管理神器!简介安装必要的插件创建 Kafka 连接第一步:创建连接第二步:选

C++11的函数包装器std::function使用示例

《C++11的函数包装器std::function使用示例》C++11引入的std::function是最常用的函数包装器,它可以存储任何可调用对象并提供统一的调用接口,以下是关于函数包装器的详细讲解... 目录一、std::function 的基本用法1. 基本语法二、如何使用 std::function

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

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