2011-04-19 100 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。

相關問題