为什么我不能从函数中返回Boost :: Scoped_ptr?

时间:2011-04-19 23:56:27

标签: c++ boost smart-pointers scoped-ptr

所以我尝试为类创建创建一些boost.extension函数的包装器。所以我创建了一个函数:

template <class BaseClass, class ConstructorType>
 boost::scoped_ptr<BaseClass> get_class (shared_library & lib, std::string class_name, ConstructorType value ) {
map<string, factory<BaseClass, ConstructorType> > lib_factories = get_factories<BaseClass, ConstructorType>(lib);
return boost::scoped_ptr<BaseClass> lib_class(lib_factories[class_name].create(value));
}

调用:

template <class BaseClass, class ConstructorType>
map<string, factory<BaseClass, ConstructorType> > get_factories (shared_library & lib) {
    type_map lib_types;
    if (!lib.call(lib_types)) {
        cerr << "Types map not found!" << endl;
        cin.get();
    }

    map<string, factory<BaseClass, ConstructorType> > lib_factories(lib_types.get());
    if (lib_factories.empty()) {
        cerr << "Producers not found!" << endl;
        cin.get();
    }
    return lib_factories;
}

但最后并不是那么重要。什么是重要的 - 我无法得到我的函数return =(

我试着这样:

boost::scoped_ptr<PublicProducerPrototype> producer = get_class<PublicProducerPrototype, int>(simple_producer, "simpleProducer", 1);

我也尝试过:

boost::scoped_ptr<PublicProducerPrototype> producer ( get_class<PublicProducerPrototype, int>(simple_producer, "simpleProducer", 1));

但是编译器让我高高在上C2248它无法调用boost::scoped_ptr<T>的某个私有成员

那么如何让我的回归...可回复//如何收到它?

2 个答案:

答案 0 :(得分:20)

boost::scoped_ptr是不可复制的。由于你不能复制scoped_ptr,你也不能返回一个(按值返回一个对象要求你能够复制它,至少在C ++ 03中)。如果需要返回智能指针所拥有的对象,则需要选择不同类型的智能指针。

如果您的编译器支持std::unique_ptr,您应该使用它(因为看起来您使用的是Visual C ++,Visual C ++ 2010支持std::unique_ptr);否则,请考虑使用std::auto_ptr{std,std::tr1,boost}::shared_ptr,具体取决于您的具体用例。

答案 1 :(得分:5)

您也可以尝试使用boost :: interprocess :: unique_ptr。