2011-04-19 63 views
4

所以我尝试创建一些包装boost.extension功能的类创建。所以,我创建了一个功能:为什么我不能从函数返回Boost :: Scoped_ptr?

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; 
} 

,但最后还不是那么重要。什么是重要的 - 我不能让我的函数返回=(

我尝试这样的方式:

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)); 

但是编译器talls我C2248它不能调用一些私人会员boost::scoped_ptr<T>

那么如何让我的退货...可以退货//如何收货呢?

+3

我的猜测,不知道更多关于错误,是复制构造函数是私有的(即该类打算是不可复制的),并且返回需要复制。你可能没有在工作中使用正确的智能指针。 – 2011-04-20 00:00:53

回答

20

boost::scoped_ptr是不可复制的。既然你不能复制一个scoped_ptr,你也不能返回一个(按照值返回一个对象,要求你能够复制它,至少在C++ 03中)。如果您需要返回智能指针所拥有的对象,则需要选择其他类型的智能指针。如果你的编译器支持std::unique_ptr,你应该使用它(因为它看起来像你使用Visual C++,Visual C++ 2010支持std::unique_ptr);如果你的编译器支持std::unique_ptr。否则,请考虑使用std::auto_ptr{std,std::tr1,boost}::shared_ptr,具体取决于您的确切用例。

+3

如果你用'auto_ptr'(它基本上只是一个破坏的'unique_ptr'),请记住它的问题 - 主要是它不兼容STL容器,比如'vector'和'map'。就个人而言,我会推荐'shared_ptr'(这是[boost的一部分](http://www.boost.org/doc/libs/1_46_1/libs/smart_ptr/smart_ptr.htm)) – 2011-04-20 00:07:36

+0

您可以使用'boost: :shared_ptr'或'std :: auto_ptr'。 – 2011-04-20 00:07:53

5

你也可以尝试boost :: interprocess :: unique_ptr。

相关问题