如何在不使用shared_ptr时让两个A对象共享同一List<B*>数据?
原代码
#include <iostream> #include <list> #include <memory> using namespace std; class B { int b; public: B(){}; B(int _b) { b = _b; } int getb() const {return b;} void setb(int _b) {b=_b;} }; class A { private: list<B*> myList; public: A() { myList.push_back(new B(5)); myList.push_back(new B(6)); myList.push_back(new B(7)); } ~A() { cout << "destructor"<<endl; } void displayData() { cout << "List Items:" << endl; for (auto& item : myList) { cout << item->getb()<<endl; } } void Set(int currentValue, int b) { for (auto& item : myList) { if (currentValue == item->getb()) { item->setb(b); break; } } } // Copy constructor A(const A &src) { for (auto& item : src.myList) { myList.push_back(new B(item->getb())); } } // Copy assignement A& operator= (const A &src) { for (auto& item : myList) { if (item != nullptr) delete item; } for (auto& item : src.myList) { myList.push_back(new B(item->getb())); } return *this; } }; int main() { A a1; A a2{a1}; a2.Set(6,9); std::cout<<"a1:" <<endl; a1.displayData(); std::cout<<"a2:" <<endl; a2.displayData(); return 0; }
原输出
a1: List Items: 5 6 7 a2: List Items: 5 9 7 destructor destructor
问题描述
当前代码中,类A的拷贝构造函数实现了深拷贝,使得对象a1与a2的List数据相互独立。现需要让a1和a2引用同一List数据,且不使用shared_ptr方案,请问如何修改类A中list<B*> myList的声明方式?
解决方案
1. 修改成员声明方式
将类A的私有成员list<B*> myList;修改为指针类型:
list<B*>* myList;
2. 配套代码调整
仅修改声明无法正常运行,还需要调整构造、拷贝构造、赋值运算符和析构函数,同时引入引用计数避免内存泄漏和双重释放问题:
修改后的类A完整代码如下:
class A { private: list<B*>* myList; int* refCount; // 引用计数,管理共享List的生命周期 public: A() { myList = new list<B*>(); // 初始化List指针 myList->push_back(new B(5)); myList->push_back(new B(6)); myList->push_back(new B(7)); refCount = new int(1); // 初始引用计数为1 } ~A() { (*refCount)--; if (*refCount == 0) { // 最后一个引用对象销毁时,清理List内的B对象和List本身 for (auto& item : *myList) { delete item; } delete myList; delete refCount; } cout << "destructor"<<endl; } void displayData() { cout << "List Items:" << endl; for (auto& item : *myList) { cout << item->getb()<<endl; } } void Set(int currentValue, int b) { for (auto& item : *myList) { if (currentValue == item->getb()) { item->setb(b); break; } } } // Copy constructor - 共享List指针,增加引用计数 A(const A &src) { myList = src.myList; refCount = src.refCount; (*refCount)++; } // Copy assignment - 共享List指针,调整引用计数 A& operator= (const A &src) { if (this == &src) return *this; // 防止自赋值 // 先减少当前对象的引用计数,若为0则清理资源 (*refCount)--; if (*refCount == 0) { for (auto& item : *myList) { delete item; } delete myList; delete refCount; } // 共享源对象的List和引用计数 myList = src.myList; refCount = src.refCount; (*refCount)++; return *this; } };
3. 修改后的运行效果
此时运行main函数,a2修改List数据后,a1的List也会同步变化,输出如下:
a1: List Items: 5 9 7 a2: List Items: 5 9 7 destructor destructor
内容的提问来源于stack exchange,提问作者Ghazi
相关产品推荐
相关产品推荐

