【C++ 学习 ⑩】- 详解 string 类(下):string 类的模拟实现和写时拷贝

news2025/2/25 0:20:39

目录

一、string 类的模拟实现

1.1 - string.h

1.2 - test.cpp

二、string 类的写时拷贝

2.1 - 示例

2.2 - 原理



一、string 类的模拟实现

1.1 - string.h

#pragma once

#include <assert.h>
#include <string.h>
#include <iostream>

namespace yzz
{
	class string
	{
	public:
		/*-------- 构造函数和析构函数 --------*/
		// 默认构造函数
		string(const char* str = "")
		{
			assert(str);  // 前提是 str 非空
			_size = strlen(str);
			_capacity = _size;
			_str = new char[_capacity + 1];
			memcpy(_str, str, _size + 1);
		}

		// 拷贝构造函数(实现深拷贝)
		string(const string& s)
			: _size(s._size), _capacity(s._capacity), _str(new char[s._capacity + 1])
		{
			memcpy(_str, s._str, _size + 1);  
			// 注意:因为字符串和 string 类对象有所区别,所以此处不能使用 strcpy
		}

		// 析构函数
		~string()
		{
			if (_str)
			{
				delete[] _str;
				_str = nullptr;
				_size = _capacity = 0;
			}
		}

		/*-------- 赋值运算符重载(实现深拷贝)--------*/
		// 1. 传统写法
		/*string& operator=(const string& s)
		{
			if (this != &s)
			{
				delete[] _str;
				_str = new char[s._capacity + 1];
				memcpy(_str, s._str, s._size + 1);

				_size = s._size;
				_capacity = s._capacity;
			}
			return *this;
		}*/

		// 2. 现代写法
		void swap(string& s)
		{
			std::swap(_str, s._str);
			std::swap(_size, s._size);
			std::swap(_capacity, s._capacity);
		}

		/*string& operator=(const string& s)
		{
			if (this != &s)
			{
				string tmp(s);  // 利用上面写好的拷贝构造函数实现深拷贝
				swap(tmp);  // 注意:经过交换后,函数结束会析构 tmp
				// 正所谓 "兔死狗烹"、"鸟尽弓藏"、"过河拆桥"
			}
			return *this;
		}*/

		// 3. 现代写法的改良版
		string& operator=(string tmp)
		{
			swap(tmp);
			return *this;
		}

		/*-------- 容量操作 --------*/
		size_t size() const
		{
			return _size;
		}

		size_t capacity() const
		{
			return _capacity;
		}

		void clear()
		{
			_str[0] = '\0';
			_size = 0;
		}

		void reserve(size_t n = 0)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n + 1];
				memcpy(tmp, _str, _size + 1);
				delete[] _str;
				_str = tmp;
				_capacity = n;
			}
		}

		void resize(size_t n, char ch = '\0')
		{
			if (n > _size)
			{
				if (n > _capacity)  // 考虑是否需要扩容
				{
					reserve(n);
				}

				for (size_t i = _size; i < n; ++i)
				{
					_str[i] = ch;
				}
			}

			_size = n;
			_str[_size] = '\0';
		}

		/*-------- 遍历及访问操作 --------*/
		char& operator[](size_t pos)
		{
			assert(pos < _size);  // 前提是 pos 合法
			return _str[pos];
		}

		const char& operator[](size_t pos) const
		{
			assert(pos < _size);  // 前提是 pos 合法
			return _str[pos];
		}

		typedef char* iterator;
		typedef const char* const_iterator;
		iterator begin()
		{
			return _str;
		}

		const_iterator begin() const
		{
			return _str;
		}

		iterator end()
		{
			return _str + _size;
		}

		const_iterator end() const
		{
			return _str + _size;
		}

		/*-------- 修改操作 --------*/
		void push_back(char ch)
		{
			if (_size == _capacity)  // 首先判断是否需要扩容
			{
				reserve(_capacity == 0 ? 5 : 2 * _capacity);  // 2 倍扩容
			}
			_str[_size++] = ch;
			_str[_size] = '\0';
		}

		void append(const char* str)
		{
			assert(str);  // 前提是 str 非空
			size_t len = strlen(str);
			if (_size + len > _capacity)  // 判断是否需要扩容
			{
				reserve(_size + len);  // 至少扩至 _size + len
			}
			memcpy(_str + _size, str, len + 1);
			_size += len;
		}

		string& operator+=(char ch)
		{
			push_back(ch);
			return *this;
		}

		string& operator+=(const char* str)
		{
			append(str);
			return *this;
		}

		void insert(size_t pos, size_t n, char ch)
		{
			assert(pos <= _size);  // 前提是 pos 合法(当 pos 等于 _size 时相当于尾插)
			if (_size + n > _capacity)  // 判断是否需要扩容
			{
				reserve(_size + n);  // 至少扩至 _size + n
			}
			// 注意:考虑 pos 为 0 的情况
			for (size_t end = _size; end != npos && end >= pos; --end)
			{
				_str[end + n] = _str[end];
			}
			for (size_t i = 0; i < n; ++i)
			{
				_str[pos + i] = ch;
			}
			_size += n;
		}

		void insert(size_t pos, const char* str)
		{
			assert(pos <= _size && str);  // 前提是 pos 合法且 str 非空
			size_t len = strlen(str);
			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}

			for (size_t end = _size; end != npos && end >= pos; --end)
			{
				_str[end + len] = _str[end];
			}
			for (size_t i = 0; i < len; ++i)
			{
				_str[pos + i] = str[i];
			}
			_size += len;
		}

		void erase(size_t pos = 0, size_t len = npos)
		{
			assert(pos < _size);  // 前提是 pos 合法
			if (len == npos || pos + len - 1 >= _size - 1)
			{
				_size = pos;
				_str[_size] = '\0';
			}
			else
			{
				for (size_t i = pos + len; i <= _size; ++i)
				{
					_str[pos++] = _str[i];
				}
				_size -= len;
			}
		}

		/*-------- 字符串操作 --------*/
		const char* c_str() const
		{
			return _str;
		}

		size_t find(char ch, size_t pos = 0) const
		{
			assert(pos < _size);  // 前提是 pos 合法
			for (size_t i = pos; i < _size; ++i)
			{
				if (_str[i] == ch)
					return i;
			}
			return npos;
		}

		size_t find(const char* str, size_t pos = 0) const
		{
			assert(pos < _size&& str);  // 前提是 pos 合法且 str 非空
			const char* ptr = strstr(_str + pos, str);
			if (ptr)
				return ptr - _str;
			else
				return npos;
		}

		string substr(size_t pos = 0, size_t len = npos) const
		{
			assert(pos < _size);  // 前提是 pos 合法

			size_t n = len;
			if (len == npos || pos + len - 1 >= _size - 1)
			{
				n = _size - pos;
			}

			string tmp;
			tmp.reserve(n);
			for (size_t i = pos; i < pos + n; ++i)
			{
				tmp += _str[i];
			}
			return tmp;
		}

		/*-------- 关系运算符重载 --------*/
		bool operator==(const string& s) const
		{
			if (_size != s._size)
				return false;

			for (size_t i = 0; i < _size; ++i)
			{
				if (_str[i] != s._str[i])
					return false;
			}
			return true;
		}

		bool operator!=(const string& s) const
		{
			return !(*this == s);
		}

		bool operator<(const string& s) const
		{
			size_t i = 0, j = 0;
			while (i < _size && j < s._size)
			{
				if (_str[i] < s._str[j])
					return true;
				else if (_str[i] > s._str[j])
					return false;
				else
					++i, ++j;
			}

			return i == _size && j != s._size;
		}

		bool operator<=(const string& s) const
		{
			return *this < s || *this == s;
		}

		bool operator>(const string& s) const
		{
			return !(*this <= s);
		}

		bool operator>=(const string& s) const
		{
			return !(*this < s);
		}
	private:
		size_t _size;
		size_t _capacity;
		char* _str;
	public:
		static const size_t npos;
	};

	const size_t string::npos = -1;

	/*-------- 流插入(<<)和流提取(>>)运算符重载 --------*/
	std::ostream& operator<<(std::ostream& out, const string& s)
	{
		for (size_t i = 0; i < s.size(); ++i)
		{
			out << s[i];
		}
		return out;
	}

	std::istream& operator>>(std::istream& in, string& s)
	{
		s.clear();  // 清空 s 中的有效字符

		// 清除缓冲区中的空白字符
		char ch = in.get();
		while (ch == ' ' || ch == '\n' || ch == '\t')
		{
			ch = in.get();
		}
		
		char buf[128] = { 0 };
		int i = 0;
		while (ch != ' ' && ch != '\n' && ch != '\t')
		{
			buf[i++] = ch;
			if (i == 127)  // buf[127] 始终等于 '\0'
			{
				s += buf;
				i = 0;
			}
			ch = in.get();
		}
		if (i != 0)
		{
			buf[i] = '\0';
			s += buf;
		}

		return in;
	}
}

注意

'\0' 是字符串的结束标志,因此在输出字符串时,遇到 '\0' 就停止输出了

而对于 string 类对象,它的成员变量 _size 表示其有效字符个数,因此在输出 string 类对象时,即便遇到 '\0' 也不会停止输出

示例

#include <iostream>
#include <string>
using namespace std;
​
int main()
{
    // 输出字符串
    const char* str = "Hello\0World";
    cout << str << endl;  // Hello
​
    // 输出 string 类对象
    string s1("Hello");
    s1 += '\0';
    s1 += "World";
    cout << s1 << endl;  // HelloWorld
    cout << s1.c_str() << endl;  // Hello
​
    string s2(s1);
    cout << s2 << endl;  // HelloWorld
    cout << s2.c_str() << endl;  // Hello
​
    string s3;
    s3 = s1;
    cout << s3 << endl;  // HelloWorld
    cout << s3.c_str() << endl;  // Hello
    return 0;
}

1.2 - test.cpp

#define _CRT_SECURE_NO_WARNINGS 1

#include "string.h"
#include <iostream>
using namespace std;

void test_string1()
{
	yzz::string s1;
	cout << s1 << endl;  // 空

	yzz::string s2("Hello");
	s2 += '\0';
	s2 += "World";
	yzz::string s3(s2);
	cout << s2 << endl;  // HelloWorld
	cout << s2.c_str() << endl;  // Hello
	cout << s3 << endl;  // HelloWorld
	cout << s3.c_str() << endl;  // Hello

	yzz::string s4;
	cin >> s4;  // 假设输入 "abcdef"
	cout << s4 << endl;  // abcdef
	cout << s4.c_str() << endl;  // abcdef

	yzz::string s5;
	s5 = s2;
	cout << s5 << endl;  // HelloWorld
	cout << s5.c_str() << endl;  // Hello
}

void test_string2()
{
	yzz::string s("hello world");
	cout << s.size() << endl;  // 11
	cout << s.capacity() << endl;  // 11

	s.clear();
	cout << s.size() << endl;  // 0
	cout << s.capacity() << endl;  // 11

	s = "hello world";
	s.reserve(20);
	cout << s.capacity() << endl;  // 20

	s.resize(5);
	cout << s << endl;  // hello
	cout << s.size() << endl;  // 5
	cout << s.capacity() << endl;  // 20

	s.resize(10, 'x');
	cout << s << endl;  // helloxxxxx
	cout << s.size() << endl;  // 10
	cout << s.capacity() << endl;  // 20
}

void test_string3()
{
	yzz::string s("01234");
	for (size_t i = 0; i < s.size(); ++i)
	{
		s[i] += 5;
		cout << s[i];
	}
	cout << endl;
	// 56789

	for (yzz::string::iterator it = s.begin(); it != s.end(); ++it)
	{
		*it -= 5;
		cout << *it;
	}
	cout << endl;
	// 01234

	for (auto& ch : s)
	{
		ch += 5;
		cout << ch;
	}
	cout << endl;
	// 56789
}

void test_string4()
{
	yzz::string s;
	s.push_back('x');
	s.push_back('y');
	cout << s << endl;  // xy

	s.append("xy");
	cout << s << endl;  // xyxy

	s += 'x';
	s += 'y';
	s += "xy";
	cout << s << endl;  // xyxyxyxy

	s.insert(0, 2, 'M');
	cout << s << endl;  // MMxyxyxyxy
	s.insert(6, "NN");
	cout << s << endl;  // MMxyxyNNxyxy

	s.erase(0, 6);
	cout << s << endl;  // NNxyxy
	s.erase(2, 10);
	cout << s << endl;  // NN
}

void test_string5()
{
	yzz::string url("https://legacy.cplusplus.com/reference/string/string/");

	size_t begin1 = 0;
	size_t end1 = url.find("://", begin1);
	yzz::string protocol;
	if (end1 != yzz::string::npos)
	{
		protocol = url.substr(begin1, end1 - begin1);
		cout << protocol << endl;  // https
	}

	size_t begin2 = end1 + 3;
	size_t end2 = url.find('/', begin2);
	yzz::string domainName, uri;
	if (end2 != yzz::string::npos)
	{
		domainName = url.substr(begin2, end2 - begin2);
		uri = url.substr(end2 + 1);
		cout << domainName << endl;  // legacy.cplusplus.com
		cout << uri << endl;  // reference/string/string/
	}
}

void test_string6()
{
	yzz::string s1("hello");
	yzz::string s2("hello");
	yzz::string s3("helloxyz");
	cout << (s1 == s2) << endl;  // 1
	cout << (s1 < s3) << endl;  // 1
	cout << (s3 > s1) << endl;  // 1
}

int main()
{
	// test_string1();
	// test_string2();
	// test_string3();
	// test_string4();
	// test_string5();
	test_string6();
	return 0;
}


二、string 类的写时拷贝

Scott Meyers 在《More Effective C++》中举了个例子:在你还在上学的时候,你的父母要你不要看电视,而去复习功课,于是你把自己关在房间里,做出一副正在复习功课的样子,其实你在干着别的诸如给班上的某位女生写情书之类的事,而一旦你的父母进来在你房间要检查你是否在复习时,你才真正捡起课本看书。这就是 "拖延战术",直到你非要做的时候才去做

当然,这种事情在现实生活中时往往会出事,但其在编程世界中摇身一变,就成为了最有用的技术,写时拷贝(Copy-On-Write,简称 COW)技术,就是 "拖延战术" 的产物

2.1 - 示例

我们可以通过下面的程序来了解 string 类的写时拷贝技术。

#include <string>
#include <stdio.h>
using namespace std;
​
int main()
{
    string s1("hello world");
    string s2(s1);
    string s3;
    s3 = s1;
    printf("s1's address:%p\n", s1.c_str());
    printf("s2's address:%p\n", s2.c_str());
    printf("s3's address:%p\n", s3.c_str());
​
    s1[0] = 'x';
    s2[0] = 'y';
    s3[0] = 'z';
    printf("After Copy-On-Write...\n");
    printf("s1's address:%p\n", s1.c_str());
    printf("s2's address:%p\n", s2.c_str());
    printf("s3's address:%p\n", s2.c_str());
    return 0;
}

这个程序的输出结果是(测试平台为 Linux):

我们可以看到,当用 s1 构造 s2,以及把 s1 赋值给 s3 时,s1、s2 和 s3 存放数据的地址都是一样的,即共享内存。而共享同一块内存的对象发生内容改变时,触发了 string 类的写时拷贝,s1 和 s2 存放数据的地址发生了改变,s3 存放数据的地址不变。修改内容才触发写时拷贝,不修改内容则不触发,这就是 "拖延战术" 的真谛,非要做的时候才去做

2.2 - 原理

string 类的写时拷贝是在浅拷贝的基础上增加了 "引用计数" 的方式来实现的。

引用计数:用来记录资源使用者的个数。在构造时,将资源的计数给成 1,每增加一个对象使用该资源,就给计数增加 1,当某个对象被销毁时,先给该计数减 1,然后再检查是否需要释放资源,如果计数为 1,说明该对象是资源的最后一个使用者,于是将资源释放,否则就不能释放,因为还有其他对象再使用该资源。

具体实现思路

每当我们为 string 类对象分配内存时,我们总是要多分配一个空间用来存放这个引用计数的值,只要发生拷贝构造或者赋值,这个空间的值就会加 1。而在修改 string 类对象时,就会查看引用计数是否为 1,如果不为 1,表示有人在共享这块内存,那么自己需要先做一份拷贝,然后把引用计数减 1。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/743489.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

mac版android studio设置字体避坑总结

1.整体主题字体设置: setting->Appearance & Behavior->Appearance->Theme: 设置主题 Use custom font:右边的数字是设置除了编辑代码去之外的字体大小 ,推荐使用AppleSystemUIFont 注意这个字体有个bug,就是如果用在终端横向会有空格: 2.设置终端字体: setting-…

PyTorch深度学习实战(5)——计算机视觉

PyTorch深度学习实战&#xff08;5&#xff09;——计算机视觉 0. 前言1. 图像表示2. 将图像转换为结构化数组2.1 灰度图像表示2.2 彩色图像表示 3 利用神经网络进行图像分析的优势小结系列链接 0. 前言 计算机视觉是指通过计算机系统对图像和视频进行处理和分析&#xff0c;利…

云计算基础教程(第2版)笔记——基础篇与技术篇介绍

文章目录 前言 第一篇 基础篇 一 绪论 1.1 云计算的概念以及特征 1.1.1云计算的基本概念 1.1.2云计算的基本特征 1.2 云计算发展简史 1.3 三种业务模式介绍 1. 基础设施即服务&#xff08;IaaS&#xff09; 2. 平台即服务&#xff08;PaaS&#xff09; 3. 软…

TypeScript 学习笔记(二):接口

一、接口的定义 在面向对象的编程中&#xff0c;接口是一种规范的定义&#xff0c;它定义了行为和动作的规范&#xff0c;在程序设计里面&#xff0c;接口起到一种限制和规范的作用。接口定义了某一批类所需要遵守的规范&#xff0c;接口不关心这些类的内部状态数据&#xff0…

spring cloud 之 openFeign

Feign和openFeign Feign Fegin使java Http客户端更加方便简洁&#xff0c; Feign集成了Ribbon、RestTemplate实现了负载均衡的执行Http调用&#xff0c;只不过对原有的方式&#xff08;RibbonRestTemplate&#xff09;进行了封装&#xff0c;开发者不必手动使用RestTemplate调…

【Linux】- Vim 编辑器、开关机、和用户权限管理常用命令

Vim 编辑器、开关机、和用户权限管理常用命令 1.1&#x1f330;vi 和 vim 的基本介绍1.2&#x1f36e;vi 和 vim 常用的三种模式1.3&#x1f320;vim的基本使用2.1&#x1f365;开机、重启2.2&#x1f37c;用户登录注销3.1&#x1f600;用户管理&#xff08;crud&#xff09;3.…

【C++算法模板】快排、归并、二分

目录 快速排序 归并排序 二分算法 整数二分 浮点数二分模板 总结&#xff1a; 快速排序 //快速排序 void quick_sort(int q[], int l, int r) {if (l > r) return;//向下取整可能使得x取到q[l]int i l - 1, j r 1, x q[l r >> 1];while (i < j){do i; …

M芯片Mac实现安卓模拟器多开

写在前面&#xff1a;博主是一只经过实战开发历练后投身培训事业的“小山猪”&#xff0c;昵称取自动画片《狮子王》中的“彭彭”&#xff0c;总是以乐观、积极的心态对待周边的事物。本人的技术路线从Java全栈工程师一路奔向大数据开发、数据挖掘领域&#xff0c;如今终有小成…

Linux kernel内存初始化介绍

early_fixmap_init&#xff1a; dtb进行映射&#xff0c;通过设备树文件和membloc模块让内核了解更为广阔的内存世界。Uboot将dtb拷贝到内存中&#xff0c;且通过传递相关参数将dtb的物理地址告知内核。但是内核必须将dtb的相关物理地址映射到虚拟地址上&#xff0c;通过虚拟地…

基于springboot的城乡医疗卫生服务系统

摘 要 网络的广泛应用给生活带来了十分的便利。所以把城乡医疗卫生服务与现在网络相结合&#xff0c;利用java语言建设城乡医疗卫生服务系统&#xff0c;实现城乡医疗卫生服务系统的信息化。则对于进一步提高医院的发展&#xff0c;丰富城乡医疗卫生服务经验能起到不少的促进作…

ModaHub魔搭社区:向量数据库Zilliz Cloud集群、Collection 及 Entity教程

目录 集群 Collection 字段 Schema 索引 Entity Zilliz Cloud 集群由全托管 Milvus 实例及相关计算资源构成。您可以在 Zilliz Cloud 集群中创建 Collection,然后在 Collection 中插入 Entity。Zilliz Cloud 集群中的 Collection 类似于关系型数据库中的表。Collection …

使用React的函数式组件实现一个具有过渡变化、刻度切换、点击高亮的柱状图DIY组件

本想使用业界大佬们开源的各种图表库&#xff08;如&#xff1a;ECharts、G2可视化引擎、BizCharts ...&#xff09;&#xff0c;但是有的需求不仅要求有过渡变化&#xff0c;还要点击某个图高亮同时发送HTTP请求数据等功能&#xff0c;着实不知道怎么把canvas或svg绘制的图表弄…

ElasticSearch入门教程

文章目录 一、Elasticsearch 概述1.1、ElasticSearch是什么&#xff1f;1.2、ElasticSearch的安装 二、ElasticSearch的使用2.1、索引操作2.2、文档操作2.3、映射操作2.4、高级查询操作 一、Elasticsearch 概述 1.1、ElasticSearch是什么&#xff1f; 官网解释如图所示&#…

Rdkit|操作分子对象

github&#xff1a;地址 文章目录 RDKit|操作分子对象引入所需库获取分子中的原子获取原子的坐标信息访问单个原子的信息访问所有原子分子中的键操作获取键的信息 获取分子中所有的环 RDKit|操作分子对象 引入所需库 from rdkit import Chem from rdkit.Chem import Draw获取…

Mysql基本语法+Navicat使用

进入数据库&#xff1a;mysql -uroot -p 修改数据库密码&#xff1a;ALTER USER rootlocalhost IDENTIFIED BY 这里输入密码; &#xff08;如&#xff1a;ALTER USER rootlocalhost IDENTIFIED BY 111111;&#xff09; 创建数据库&#xff1a;create database 数据库名; 查…

刷题记录01

题目一. 这道题要先解释一下什么是非递增,非递增就是a[i] >a[i1],递增则是相反. 非递减就是a[i]>a[i1],递减就是相反 大方向思路是: 遍历数组判断相邻元素的顺序关系统计排序子序列数量 具体思路: 本题依次比较整个数组a[i1]>a[i] &#xff0c;则进入非递增序列判…

在vue中点击弹框给弹框中的表格绑值

场景描述&#xff1a;如下图所示&#xff0c;我们需要点击 ‘账单生成’ 按钮&#xff0c;然后里边要展示一个下图这样的表格。 最主要的是如何展示表格中的内容&#xff0c;一起看看吧&#xff01; <template><!-- 水费 欠费--><el-dialog title"水费欠费…

静态图片转3D动态GIF/视频

Leiapix是一项令人印象深刻的技术&#xff0c;它可以让静态的图片动起来&#xff0c;为观众提供沉浸式和交互式的图像体验。这项创新的技术使用了Leia Inc.的自适应光栅屏幕技术&#xff0c;通过利用人眼的视差和立体视觉效应&#xff0c;将图像中的元素以动态的方式呈现出来&a…

《第一次线下面试总结》

《第一次线下面试总结》 面试时间&#xff1a;2023/7/11 上午10点 面试总时长20分钟。 实习薪资&#xff1a;2.3k…后期看表现&#xff0c;可根据实际情况那啥 。估计是看锤子… 一、HR面 自我介绍你哪里的、目前住哪里等基本信息。你偏向前端还是后端&#xff1f;说说你的项目…

电路分析基础学习(上)第7章

李瀚荪版电分第二版 目录 二阶电路的定义 电路中的等幅振荡与阻尼振荡 RLC电路的零输入响应 ----------------------------------------------------------------------------------------------------------------------------- 二阶电路的定义 二阶电路是指由电容、电感…