繁体   English   中英

具有责任转移的转换构造函数

[英]Conversion constructor with responsibility transfer

这是对这个问题的跟进。

我需要实现一个转换操作,将成员对象的责任从一个对象传递给另一个对象。 转换操作发生在类层次结构中。 有一个Base类和两个派生类,说Child1Child2 Base类中,有一个动态创建的对象,我需要从通过Child1Child2 (与责任一起),而发生转换,而不是让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项目,因此可能无法使用智能指针或增强库(我不知道) - 我只记得这可能是一个解决方案,但我还没有使用它们。

我认为你需要查看引用计数的对象。 本质上,对象本身跟踪它的用法本身,而不是将原始指针存储到对象,而是使用引用计数指针。

Scott Meyers在这里谈到这个:

http://www.aristeia.com/BookErrata/M29Source.html

当你在嵌入式系统上时,我不确定你是否可以使用boost::shared_ptr<>但是没有什么能阻止你实现这一点,因为Meyers概述了这一点。

因此,不是在基类中有一个指向相关对象的原始指针,而是有一个共享指针/引用计数指针,一旦将对象复制到Child2 ,就会阻止删除对象。 通过构造Child2,它将有2个引用,因此当Child1被删除时不会死亡。 但是,当Child2被删除时。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM