簡體   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