12

pythonwithステートメントに似たものをC++で実装しようとしています。主にQt-OpenGLで使用する予定なので、メソッドはbindand release(python__enter__では__exit__)と呼ばれます。

私が思いついたコード:

ヘッダ:

#include <iostream>
#include <vector>

class With
{
public:
    class A
    {
    public:
        virtual ~A() { }
    };

    template <typename T>
    class B : public A
    {
    public:
        B(T& _t) : t(_t)
        {
            t.bind();
        }

        virtual ~B()
        {
            t.release();
        }

        T& t;
    };

    template <typename... Args>
    With(Args&... args)
    {
        set(args...);
    }

    ~With();

    template <typename T, typename... Args>
    void set(T& t, Args&... args)
    {
        set(t);
        set(args...);
    }

    template <typename T>
    void set(T& t)
    {
        a.push_back(dynamic_cast<A*>(new B<T>(t)));
    }

    std::vector<A*> a;
};

cpp:

With::~With()
{
    for (auto it = a.begin(); it != a.end(); ++it)
    {
        delete *it;
    }
}

使用法:

class X
{
public:
    void bind() { std::cout << "bind x" << std::endl; }
    void release() { std::cout << "release x" << std::endl; }
};

class Y
{
public:
    void bind() { std::cout << "bind y" << std::endl; }
    void release() { std::cout << "release y" << std::endl; }
};

int main()
{
    X y;
    Y y;

    std::cout << "start" << std::endl;
    {
        With w(x, y);
        std::cout << "with" << std::endl;
    }

    std::cout << "done" << std::endl;

    return 0;
}

質問:

  1. 必要と少し不器用class Aに感じます。class Bより良い代替案はありますか?
  2. &&代わりに使用することの欠点はあり&ますか?一時的なオブジェクトの使用が可能になります(例With w(X(), y);
4

3 に答える 3

13

with ステートメントは、C++ で既に通常行われていることを Python で実行する方法です。RAIIといいます:リソース取得は初期化です。

Python では、クラス オブジェクトが作成されると、__init__メソッドが呼び出されます (ただし、これは厳密な保証ではありません)。この__del__メソッドは、オブジェクトが使用されなくなった後、ある時点でガベージ コレクターによって呼び出されますが、決定論的ではありません。

C++ では、明確に定義された時点でデストラクタが呼び出されるため、with.

クラス B のようなものを使用することをお勧めします(クラス A や With は必要ありません)。

template <typename T>
class B {
public:
    B(T& t) : m_t(t){
        m_t.bind();
    }
    ~B() {
        m_t.release();
    }
    T& m_t;
}

次のように使用します。

{
    B<X> bound_x(x);  // x.bind is called
    B<Y> bound_y(y);  // y.bind is called
    // use x and y here
} // bound_x and bound_y is destroyed here 
  // so x.release and y.release is called    
于 2012-07-15T16:59:32.860 に答える
2

それは言語と共に出荷され、RAII と呼ばれます。

struct X {
    X() { std::cout << "bind\n"; }
    ~X() { std::cout << "release\n"; }
};
int main() {
    X x;
}
于 2012-07-15T17:16:52.683 に答える