简体   繁体   English

如何创建需要上下文的对象的全局实例?

[英]How to create global instance of objects that require a context?

I am attempting to write a C++ wrapper of OpenVG, which is very Open-GL like in its design. 我正在尝试编写一个OpenVG的C ++包装器,它的设计非常像Open-GL。 here is a simple wrapper for a path handle: 这是一个路径句柄的简单包装器:

class Path {
        VGPath handle;

    public:
        Path() :
        handle(vgCreatePath(VG_PATH_FORMAT_STANDARD, VG_PATH_DATATYPE_F,
            1,0,0,0, VG_PATH_CAPABILITY_ALL)) 
        { 
        std::cout << "Path Handle created : " << (void*)handle << '\n';
        }

        ~Path() {
            std::cout << "Path destroyed  : " << (void*)handle << '\n';
            vgDestroyPath(handle);
        }

    };

unfortunately, openVG requires a context to function and will abort if vgCreatePath is called with no openVG context. 不幸的是,openVG需要一个上下文来运行,如果在没有openVG上下文的情况下调用vgCreatePath ,它将中止。 This prevents me from creating (for testing purpose) a global Path object object in my code, since it is build before I can create a openVG context (I do so in the main). 这使我无法在我的代码中创建(用于测试目的)全局Path对象,因为它是在我创建openVG上下文之前构建的(我在main中这样做)。 Is there any workaround to prevent this? 有什么办法可以防止这种情况发生吗?

I think that leaving the handle unitialized at the object construction is a very bad idea... should I force the creation of a global context when I'm creating a Path object if no context is present? 我认为将句柄保留在对象构造中是一个非常糟糕的主意......当我创建一个Path对象时,如果没有上下文,我应该强制创建一个全局上下文吗?

Is there any workaround to prevent this? 有什么办法可以防止这种情况发生吗?

Yes, use smart pointers, create it on demand using some kind of "factory" function, store it as long as it is needed in any variable. 是的,使用智能指针,使用某种“工厂”功能按需创建它,只要在任何变量中需要它就存储它。

In C++03: 在C ++ 03中:

typedef boost::weak_ptr<Path> PathWeakPtr;
typedef boost::shared_ptr<Path> PathPtr;

PathPtr createPath(){
    static PathWeakPtr lastPath;
    PathPtr result = lastPath.lock();
    if (!result){
        result.reset(new Path());
        lastPath = result;
    }
    return result;
}

... ...

void doSomething(){
    PathPtr path = createPath();//points to same path as in main*()
    ...
}

int main(int argc, char** argv){
    PathPtr path = createPath();//initialization
    doSomething();
    return 0;
}

In C++11 use: 在C ++ 11中使用:

typedef std::weak_ptr<Path> PathWeakPtr;
typedef std::shared_ptr<Path> PathPtr;

instead of 代替

typedef boost::weak_ptr<Path> PathWeakPtr;
typedef boost::shared_ptr<Path> PathPtr;

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

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