Click here to Skip to main content
15,887,856 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I tried to implement a templated factory pattern but could not get it to work. Not sure if this was because I used smart pointers.

This is my code:
C++
class ObjMgr
{
public:
    static ObjMgr & Instance();
    template <typename T>
    void Register(const char* name) {
        m_creators[name] = &(ObjCreator<T>);
    }
    Abstract &
        GetObj(const string& objTypeCode);

private:
    ObjMgr(void) {};

    template <typename T>
    static shared_ptr<Abstract>& ObjCreator() {
        return move(std::shared_ptr<Abstract> (new T));
    }
    typedef shared_ptr<Abstract>& (*PObjCreator)();
    std::unordered_map<std::string, PObjCreator> m_creators;

    vector< shared_ptr<Abstract> > m_objs;

    //singleton
    static unique_ptr<ObjMgr> m_instance;
    static std::once_flag m_onceFlag;
    ObjMgr(const ObjMgr &) = default;
    ObjMgr& operator=(const ObjMgr &) = default;
};

Abstract& ObjMgr::GetObj(const string& objTypeCode)
{
    const shared_ptr<Abstract>& obj = m_creators[objTypeCode]();
    m_objs.push_back(move(obj));

    return *(m_objs.back());
}

The code compiles but at runtime, a null reference was returned by GetObj.

In main(), a derived type is registered as
C++
objMgr.Register<Derived>("Derived");

BTW, I used a vector to hold the objects so that I could later recycle the object of the same type.
Could someone tell me what I did wrong and show me how I could correct it?
Posted
Comments
CHill60 22-Oct-15 19:09pm    
Have you tried stepping through the code in the debugger, understanding what is happening with each line of code, examined the variables at each stage?
Member 12034185 23-Oct-15 9:42am    
I did, but not into STL `memory` since I could not figure what is going on inside it. Up to push_back obj was a valid object. Once inside the vector, it became a null object, so the change occurred in STL `memory`.
nv3 23-Oct-15 16:11pm    
With just looking at a tiny fraction of the code involved it seems rather hard to tell what exactly went wrong.
Andreas Gieriet 25-Oct-15 10:28am    
What is the definition of Abstract?
Why do you use shared_ptr and move?
I would store plain pointers and return a reference to the object.
Regards
Andi

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900