String类的写时拷贝实例
2019/7/10 22:50:54
本文主要是介绍String类的写时拷贝实例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
实例如下:
#include<iostream> using namespace std; class String; ostream& operator<<(ostream &out, const String&s); //引用计数器类 class String_rep { friend class String; friend ostream& operator<<(ostream &out, const String&s); public: String_rep(const char *str ) :use_count(0) { if (str == NULL) { data = new char[1]; data[0] = '\0'; } else { data = new char[strlen(str) + 1]; strcpy(data, str); } } String_rep(const String_rep &rep) :use_count(0) { data = new char[strlen(rep.data) + 1]; strcpy(data, rep.data); } String_rep& operator=(const String_rep &rep) { if (this != &rep) { delete[]data; data = new char[strlen(rep.data) + 1]; strcpy(data, rep.data); } return *this; } ~String_rep() { delete[]data; data = NULL; } public: void increase() { ++use_count; } void decrease() { if (use_count == 0) { delete this; //自杀行为 释放this所指的空间,在释放之前调动这个类的析构函数 } } private: char *data; int use_count; }; //////////////////////////////////////////////////////////////////////////////////////// class String { friend ostream& operator<<(ostream &out, const String&s); public: String(const char* str = " ") { rep = new String_rep(str); rep->increase(); } String(const String &s) { rep = s.rep; //浅拷贝 rep->increase(); } String& operator=(const String &s) { if (this != &s) { rep->decrease(); //模拟delete rep = s.rep; //模拟new rep->increase(); //模拟strcpy /*rep = s.rep; //这会更改引用计数器指针 ,造成s内存泄漏 rep->increase();*/ } return *this; } ~String() { rep->decrease(); } public: void to_upper() { if (rep->use_count > 1) { String_rep* new_rep = new String_rep(rep->data); rep->decrease(); rep = new_rep; rep->increase(); } char* ch = rep->data; while (*ch != '\0') { *ch -= 32; ++ch; } } private: String_rep *rep; //引用计数器 }; ostream& operator<<(ostream &out, const String&s) { out << s.rep->data; return out; } void main() { String s1("hello"); String s2(s1); String s3; s3 = s2; cout << "s1=" << s1 << endl; cout << "s2=" << s2 << endl; cout << "s3=" << s3 << endl; s2.to_upper(); cout << "-----------------------------------------------" << endl; cout << "s1=" << s1 << endl; cout << "s2=" << s2 << endl; cout << "s3=" << s3 << endl; }
以上这篇String类的写时拷贝实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持找一找教程网。
这篇关于String类的写时拷贝实例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-17zero-shot-learning-definition-examples-comparison
- 2024-06-06Package Easy(基于 NSIS 的打包exe安装包工具)使用方法-icode9专业技术文章分享
- 2024-06-06基于 casdoor 的 ELK 开源登录认证解决方案: elk-auth-casdoor-icode9专业技术文章分享
- 2024-05-29Elasticsearch慢查询日志配置
- 2024-05-29揭秘华为如此多成功项目的产品关键——Charter模板
- 2024-05-29海外IDC业务拓展的7大挑战
- 2024-05-29InLine Chat功能优化对标Github Copilot,CodeGeeX带来更高效、更直观的编程体验!
- 2024-05-29CodeGeeX 智能编程助手 6 项功能升级,在Visual Studio插件市场霸榜2周!
- 2024-05-29AutoMQ 生态集成 Apache Doris
- 2024-05-292024年IDC行业的深度挖掘:机遇、挑战与未来展望