C++ 用智慧指標這樣包裝 this 指標是否可行

double64發表於2024-07-16
#include <iostream>
#include <memory>

using namespace std;

class A;
class B
{
public:
    B(shared_ptr<A> a)
    {
        pa = a;
        cout << "B 構造..." << endl;
    }
    ~B()
    {
        cout << "B 析構..." << endl;
    }
    shared_ptr<A> pa;

public:
    void Hello()
    {
        cout << "hello I am B Obj." << endl;
    }
};

class C
{
public:
    C(shared_ptr<A> a)
    {
        pa = a;
        cout << "C 構造..." << endl;
    }
    ~C()
    {
        cout << "C 析構..." << endl;
    }
    shared_ptr<A> pa;

public:
    void Hello()
    {
        cout << "hello I am C Obj." << endl;
    }
};

class A
{
public:
    A()
    {
        cout << "A 構造..." << endl;
        self = shared_ptr<A>(this, [](A* a) { cout << "跳過 delete." << endl; });
        pb = make_shared<B>(self);
        pc = make_shared<C>(self);
    }
    ~A()
    {
        cout << "A 析構..." << endl;
    }
    shared_ptr<B> pb;
    shared_ptr<C> pc;
private:
    shared_ptr<A> self;
public:
    void Hello()
    {
        cout << "hello I am A Obj." << endl;
    }
};

int main()
{
    auto a = make_shared<A>();

    a->pb->Hello();
    a->pc->Hello();
    a->pb->pa->Hello();
    a->pc->pa->Hello();

    system("pause");
    return 0;
}

輸出:

A 構造...
B 構造...
C 構造...
hello I am B Obj.
hello I am C Obj.
hello I am A Obj.
hello I am A Obj.
請按任意鍵繼續. . .
A 析構...
C 析構...
B 析構...
跳過 delete.

.exe (程序 1940)已退出,程式碼為 0。
要在除錯停止時自動關閉控制檯,請啟用“工具”->“選項”->“除錯”->“除錯停止時自動關閉控制檯”。
按任意鍵關閉此視窗. . .

相關文章