这是对this问题的跟进。
我需要实现转换操作,以将成员对象的职责从一个对象传递到另一个对象。转换操作发生在类层次结构中。有一个Base
类和两个派生类,比如Child1
和Child2
。在Base
类中,有一个动态创建的对象,我需要在转换发生时从Child1
传递到Child2
(以及责任),而不是Child1
的析构者摧毁它。我写了一个简单的例子来说明我想要实现的目标:
#include <iostream>
using namespace std;
class Base {
public:
Base() {
p_int = new int; *p_int = 0;
cout << "In Base constructor, reserving memory." << endl;
}
Base(const Base& other) : p_int(other.p_int), a(other.a) {
cout << "In Base copy-constructor." << endl;
}
virtual ~Base() { delete p_int; p_int = NULL; cout << "Freeing memory." << endl; }
void setpInt(int val) { *p_int = val; }
void setInt(int val) { a = val; }
virtual void print() {
cout << "Base: ";
cout << (long)p_int << ":" << *p_int << " " << a << endl;
}
protected:
int* p_int;
int a;
};
class Child1 : public Base {
public:
Child1() : Base() {};
Child1(const Base& base) : Base(base) {}
void print() {
cout << "Child1: ";
cout << (long)p_int << ":" << *p_int << " " << a << endl;
}
};
class Child2 : public Base {
public:
Child2() : Base() {};
Child2(const Base& base) : Base(base) {}
void print() {
cout << "Child2: ";
cout << (long)p_int << ":" << *p_int << " " << a << endl;
}
};
int main() {
Child1* c1 = new Child1();
c1->setpInt(3);
c1->setInt(2);
c1->print();
Child2* c2 = new Child2(*c1);
c2->print();
delete c1; //Obviously c1's destructor is called here.
c2->print();
delete c2;
return 0;
}
结果是:
In Base constructor, reserving memory.
Child1: 158711832:3 2
In Base copy-constructor.
Child2: 158711832:3 2
Freeing memory.
Child2: 158711832:0 2
Freeing memory.
有没有办法以干净的方式做我想做的事情?我无法复制构造p_int
,因为它非常沉重。该项目是一个嵌入式的AVR项目,因此可能无法使用智能指针或增强库(我不知道) - 我只记得这可能是一个解决方案,但我还没有使用它们。 / p>
答案 0 :(得分:2)
我认为您需要查看引用计数对象。本质上,对象本身跟踪它的用法本身,而不是存储指向对象的原始指针,而是使用引用计数指针。
Scott Meyers在这里谈到这个:
http://www.aristeia.com/BookErrata/M29Source.html
当你在嵌入式系统上时,我不确定你是否可以使用boost::shared_ptr<>
但是没有什么可以阻止你实现这一点,就像Meyers概述的那样。
因此,不是在基类中有一个指向相关对象的原始指针,而是有一个共享指针/引用计数指针,一旦将对象复制到Child2
,就会阻止删除对象。通过构造Child2,它将有2个引用,因此当Child1被删除时不会死亡。但是,当Child2被删除时。