fereria
1/2/2021 - 3:18 PM

Reference Counting

/*
Reference counting
https://graphics.pixar.com/usd/docs/api/ref_ptr_8h.html

サンプルを参考に動作を確認
*/

#include <iostream>
#include <string>

#include "pxr/base/tf/refPtr.h"

using namespace pxr;
using namespace std;

typedef TfRefPtr<class Simple> SimpleRefPtr;

class Simple : public TfRefBase
{
public:
    void Method1();
    string Method2();

    static SimpleRefPtr New(string name)
    {
        return TfCreateRefPtr(new Simple(name));
    }

private:
    Simple(string name);
    ~Simple();
    
    string name;
};

Simple::Simple(string name)
{
    this->name = name;
}
Simple::~Simple()
{
    cout << "delete " << name << endl;
}

void Simple::Method1()
{
    cout << "Method1" << endl;
}

string Simple::Method2()
{
    return name;
}

void main()
{
    SimpleRefPtr p1; // null
    SimpleRefPtr p2 = Simple::New("A");
    SimpleRefPtr p3 = Simple::New("B");
    cout << p2->Method2() << endl;
    cout << p3->Method2() << endl;
    // 入れ替え
    p3.swap(p2);
    cout << p2->Method2() << endl;
    cout << p3->Method2() << endl;
    // これで Bが消える
    cout <<  "---" << endl;
    p2 = p3;
    cout << "---" << endl;
    {
        SimpleRefPtr p4 = Simple::New("C");
        cout << p4->Method2() << endl;
    }// ここを抜けると C が消える
    // main が終わると A が消える
}