实现string类

news/2025/12/14 12:22:58/文章来源:https://www.cnblogs.com/peifx/p/19227994

 

#pragma once#include <cstddef>
#include <cstring>
#include <algorithm>
#include <stdexcept>// namespace M {
class string {
public:static const size_t s_min_capacity;
private:char* data_;        // 字符串数据size_t size_;       // 字符串长度size_t capacity_;   // 容量// 重新分配内存的辅助函数void realloc_data(size_t new_cap) {new_cap = std::max(new_cap, s_min_capacity);char* new_data = new char[new_cap + 1];if (size_ > 0) {std::memcpy(new_data, data_, size_);}new_data[size_] = '\0';delete[] data_;data_ = new_data;capacity_ = new_cap;  // capacity_存储用户数据容量
    }public:// 默认构造函数string() : size_(0), capacity_(s_min_capacity) {data_ = new char[capacity_ + 1];data_[0] = '\0';}// 从C风格字符串构造string(const char* str) {if (!str) {throw std::invalid_argument("null pointer");}size_ = std::strlen(str);capacity_ = std::max(size_, s_min_capacity);data_ = new char[capacity_ + 1];std::memcpy(data_, str, size_ + 1);}// 二进制安全的构造函数string(const void* data, size_t len) {if (!data) {throw std::invalid_argument("null pointer");}size_ = len;capacity_ = std::max(len, s_min_capacity);data_ = new char[capacity_ + 1];std::memcpy(data_, data, len);data_[len] = '\0';}// 拷贝构造函数string(const string& other) : size_(other.size_), capacity_(other.capacity_) {data_ = new char[capacity_ + 1];std::memcpy(data_, other.data_, size_ + 1);}// 移动构造函数string(string&& other) noexcept : data_(other.data_), size_(other.size_), capacity_(other.capacity_) {other.data_ = nullptr;other.size_ = 0;other.capacity_ = 0;}// 析构函数~string() {delete[] data_;}// 拷贝赋值运算符string& operator=(const string& other) {if (this != &other) {char* new_data = new char[other.capacity_ + 1];std::memcpy(new_data, other.data_, other.size_ + 1);delete[] data_;data_ = new_data;size_ = other.size_;capacity_ = other.capacity_;}return *this;}// 移动赋值运算符string& operator=(string&& other) noexcept {if (this != &other) {delete[] data_;data_ = other.data_;size_ = other.size_;capacity_ = other.capacity_;other.data_ = nullptr;other.size_ = 0;other.capacity_ = 0;}return *this;}// 预分配内存void reserve(size_t new_cap) {if (new_cap > capacity_) {realloc_data(new_cap);}}// 释放多余内存void shrink_to_fit() {if (capacity_ > size_) {realloc_data(size_);}}// append 函数string& append(const char* str, size_t len) {if (!str) throw std::invalid_argument("null pointer");if (size_ + len > capacity_) {reserve((size_ + len) * 2);}std::memcpy(data_ + size_, str, len);size_ += len;data_[size_] = '\0';return *this;}string& append(const char* str) {if (!str) throw std::invalid_argument("null pointer");return append(str, std::strlen(str));}// 获取数据const char* c_str() const noexcept { return data_; }const char* data() const noexcept { return data_; }size_t size() const noexcept { return size_; }size_t capacity() const noexcept { return capacity_; }bool empty() const noexcept { return size_ == 0; }
};
// } // namespace M
const size_t string::s_min_capacity = 15;
View Code

 

测试:

#include <cassert>
#include <iostream>
#include <cstring>
#include "string.h"// 用于测试的辅助函数
#define TEST_CASE(name) \do { \std::cout << "Running test case: " << #name << "... "; \test_##name(); \std::cout << "PASSED" << std::endl; \} while (0)// 测试构造函数
void test_constructors() {// 默认构造string s1;assert(s1.empty());assert(s1.size() == 0);assert(s1.capacity() == 15);assert(s1.c_str()[0] == '\0');// C风格字符串构造string s2("hello");assert(s2.size() == 5);assert(s2.capacity() >= 5);assert(strcmp(s2.c_str(), "hello") == 0);// 二进制安全构造char data[] = {'H', 'e', 'l', 'l', 'o', '\0', 'W', 'o', 'r', 'l', 'd'};string s3(data, 11);assert(s3.size() == 11);assert(memcmp(s3.data(), data, 11) == 0);// nullptr 检查try {string s4(nullptr);assert(false);  // 不应该到达这里} catch (const std::invalid_argument&) {// 预期的异常
    }
}// 测试拷贝操作
void test_copy_operations() {string s1("hello");// 拷贝构造string s2(s1);assert(strcmp(s2.c_str(), "hello") == 0);assert(s1.c_str() != s2.c_str());  // 深拷贝检查// 拷贝赋值string s3;s3 = s1;assert(strcmp(s3.c_str(), "hello") == 0);assert(s1.c_str() != s3.c_str());  // 深拷贝检查
}// 测试移动操作
void test_move_operations() {// 移动构造string s1("hello");const char* original_data = s1.c_str();string s2(std::move(s1));assert(s2.c_str() == original_data);  // 数据被移动assert(s1.empty());                   // s1 被清空assert(s1.c_str() == nullptr);       // s1 的指针被置空// 移动赋值string s3;s3 = std::move(s2);assert(s3.c_str() == original_data);  // 数据被移动assert(s2.empty());                   // s2 被清空assert(s2.c_str() == nullptr);       // s2 的指针被置空
}// 测试容量管理
void test_capacity_management() {string s;assert(s.capacity() == 15);  // 初始容量
    s.reserve(20);assert(s.capacity() >= 20);s.append("hello");size_t cap = s.capacity();s.shrink_to_fit();assert(s.capacity() == 15);  // 回到最小容量
}// 测试 append 操作
void test_append_operations() {string s;// 普通appends.append("hello");assert(strcmp(s.c_str(), "hello") == 0);// 触发扩容的appends.append(" world");assert(strcmp(s.c_str(), "hello world") == 0);// 二进制数据appendchar binary[] = {'!', '\0', '!'};s.append(binary, 3);assert(s.size() == 14);assert(memcmp(s.data() + 11, binary, 3) == 0);
}// 测试边界条件
void test_edge_cases() {// 空字符串string s1("");assert(s1.size() == 0);assert(s1.c_str()[0] == '\0');// 大量数据std::string long_str(1000, 'x');string s2(long_str.c_str());assert(s2.size() == 1000);assert(memcmp(s2.data(), long_str.c_str(), 1000) == 0);
}// 测试异常安全性
void test_exception_safety() {// 测试空指针try {string s1(nullptr);assert(false);} catch (const std::invalid_argument&) {}try {string s2;s2.append(nullptr);assert(false);} catch (const std::invalid_argument&) {}
}int main() {TEST_CASE(constructors);TEST_CASE(copy_operations);TEST_CASE(move_operations);TEST_CASE(capacity_management);TEST_CASE(append_operations);TEST_CASE(edge_cases);TEST_CASE(exception_safety);std::cout << "\nAll tests passed!" << std::endl;return 0;
}
View Code

 

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

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2025年甘肃广告策划服务综合推荐排行榜

摘要 随着数字化转型加速,2025年甘肃广告策划行业迎来新一轮发展机遇,本土服务商在创意能力、技术应用和服务体系方面持续升级。本文基于市场调研、客户反馈和行业数据,为您呈现甘肃地区广告策划服务商综合实力排行…

2025年甘肃兰州专业的广告物料制作公司推荐

摘要 随着数字化转型的加速和线下体验经济的崛起,2025年甘肃兰州广告物料制作行业迎来新一轮发展机遇。本地市场需求持续增长,对创意设计、工艺质量和一站式服务的要求显著提升。本文基于行业数据、客户口碑和技术实…

2025年甘肃兰州比较好的广告物料制作服务团队

摘要 2025年,甘肃兰州广告物料制作行业持续蓬勃发展,随着数字化和个性化需求增长,本地服务商在技术、创意和执行层面不断升级。本文基于行业数据和用户口碑,为您推荐排名前十的广告物料制作服务团队,并提供详细分…

OpenAI Agent Kit 全网首发深度解读与上手指南 - 详解

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

supabase

supabase https://github.com/supabase/supabaseSupabaseSupabase is the Postgres development platform. Were building the features of Firebase using enterprise-grade open source tools.Hosted Postgres Datab…

2025年加工型辣椒种子生产厂家排名前十:权威评测与选择攻略

摘要 随着2025年加工型辣椒种子行业的持续增长,市场需求聚焦于高品质、高产量品种。本文基于行业数据和市场调研,整理了前十名供应商排名,涵盖品牌介绍、核心优势及服务成果,并为种植户提供实用选择指南。排名表单…

2025年加工型辣椒种子品牌前十强排行榜:镇江市镇研种业有限公司领跑行业

摘要 2025年加工型辣椒种子行业迎来高速发展,随着农业现代化和食品加工需求增长,优质种子成为种植户的核心关注点。本文基于市场调研和数据统计,为您呈现2025年加工型辣椒种子品牌排行榜前十强,重点推荐镇江市镇研…

2025年螺丝椒种子品牌综合实力排行榜前十强揭晓

摘要 随着农业现代化进程加速,螺丝椒种子行业在2025年迎来新一轮发展机遇。本文基于品种研发实力、市场占有率、用户口碑等维度,对国内主流螺丝椒种子品牌进行综合评估,为种植户提供权威参考。文末附有详细选购指南…

2025年线椒种子品牌前十强排名:专业选购指南与厂家实力解析

摘要 2025年线椒种子行业迎来技术升级与品质革新,随着种植技术的不断提升和市场需求的多样化,优质种子供应商成为产业发展的关键推动力。本文基于市场调研和行业数据分析,为您呈现当前线椒种子品牌的综合排名,并提…

2025年辣椒种子品牌前十强排行榜及深度解析

摘要 2025年辣椒种子行业持续发展,技术创新和品种优化成为市场主流,种植户对高品质种子的需求日益增长。本文基于市场调研和用户反馈,整理了2025年辣椒种子品牌排名前十的列表,为种植户和采购商提供参考。列表包括…

docker - 6 docker 部署 net core

1 最简单部署容器化 .net core 发布# 请参阅 https://aka.ms/customizecontainer 以了解如何自定义调试容器,以及 Visual Studio 如何使用此 Dockerfile 生成映像以更快地进行调试。# 此阶段用于在快速模式(默认为调试…

详细介绍:系统同步输出延迟分析(七)

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

fastdfs版本编译升降版本

原fastdfs版本源码编译docker run -d --restart=always --privileged=true --net=host --name=fastdfs5 -e FASTDFS_IPADDR=10.40.17.249 -e WEB_PORT=8080 -v /data/fdfs/fastdfs:/home/fdfs registry.harbor.com:584…

增强现实(AR)在订单拣选中的应用:便捷的技术解析与中国市场前景

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

单核超 i9、多核追 i5,2024 Mac mini M4

https://post.smzdm.com/p/a86d56pn/ 从性能对标来看, Mac mini M4 的 CPU 单核性能超越英特尔酷睿 i9 - 14900K,在 Geekbench 6 测试中,M4 单核跑分高达 3800 多分,而 i9 - 14900K 约为 3500 分 多核性能方面,M4…

Infineon GaN 基础知识

Infineon GaN 基础知识2025-11-16 13:00 斑鸠,一生。 阅读(0) 评论(0) 收藏 举报

从Transformer到LLaMA:AI大模型工程化实践完整路径解析

完整的大模型技术指南:涵盖Transformer机制详解、主流模型对比分析,实战演示LLaMA/GLM4训练微调与推理部署流程,包含LangChain应用开发、RAG系统实现、Prompt工程技巧,配套多个企业级应用场景的完整代码。大模型AP…

2025年11月安徽学历提升服务排行情况

摘要 随着职业教育政策的持续利好,2025年安徽省学历提升市场规模预计突破50亿元,在职人员学历提升需求同比增长32%。本文基于教育部备案数据、用户满意度调研及服务覆盖率指标,发布安徽省学历提升服务权威排行榜单。…

2025年国内成人自考机构推荐几家?这份权威榜单给你答案

摘要 2025年国内成人自考教育行业迎来新一轮发展机遇,随着终身学习理念的普及和职业发展需求的提升,成人自考市场规模持续扩大。本文基于权威数据分析和用户口碑评价,为您精选十家优质成人自考机构,并提供详细对比…

完整教程:OSP-0.3.1开源软件包的解压缩与分析

完整教程:OSP-0.3.1开源软件包的解压缩与分析2025-11-16 12:47 tlnshuju 阅读(0) 评论(0) 收藏 举报pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: …