[C++-sig] Object lifetime issue

Matt Holmes tegan at gnometank.net
Tue Sep 11 00:58:23 CEST 2007


Roman Yakovenko wrote:
> On 9/2/07, *Matt Holmes* <tegan at gnometank.net 
> <mailto:tegan at gnometank.net>> wrote:
> 
>     I am trying to expose one of the classes in my engine as an abstract
>     class that is used as the base for a series of Python classes.
> 
>     That class is called InputCommand and is defined as such:
>     namespace Stasis {
>             class InputCommand {
>             public:
>                     virtual bool execute() = 0;
>             };
>     }
> 
>     To expose that class, I created the following wrapper:
> 
>     class InputCommandWrapper : public Stasis::InputCommand, public
>     wrapper<Stasis::InputCommand> {
>     public:
>             bool execute() {
>                     return this->get_override("execute")();
>             }
>     };
> 
>     And added it to my Boost.Python module like so:
> 
>     class_<InputCommandWrapper, boost::noncopyable>("InputCommand")
>             .def("execute", pure_virtual(&InputCommand::execute));
> 
>     Everything seems okay so far, but then I have another class called
>     InputManager. This class exposes a function, registerCommand, that takes
>     a const std::string& and an InputCommand*. That classes partial
>     defintion is:
> 
>     class InputManager : public Singleton<InputManager>
>     public:
>             static InputManager& getSingleton() { return *ms_Singleton; }
>             static InputManager* getSingletonPtr() { return ms_Singleton; }
> 
>             InputManager();
>             ~InputManager();
> 
>             void executeCommand(const string& cmdName);
>             void registerCommand(const string& cmdName, InputCommand* cmd);
>     }
> 
> 
> 
> Who is responsible for cmd lifetime, InputManager or somebody else? This 
> answer is a key for correct solution.
> 
> I attached 2 files that contains solution for your problem
> 
> P.S. The code is not minimal, because I extracted it from Py++ unittests
> 
> -- 
> Roman Yakovenko
> C++ Python language binding
> http://www.language-binding.net/
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig


My apologies for not getting back to you on this sooner. InputManager 
will own the command objects. Currently one of the previous posters 
solution of having a duplicate() method that returns a new object of the 
given type works, but commands have no state, so I am okay with that. 
Later in my engine development, I will need objects that are created in 
Python to be owned by the C++ code and not have them duplicated, as I 
will need the exact objects and their state as processed by Python code. 
I will give your solution a look, thank you!.



More information about the Cplusplus-sig mailing list