How do I clean up the classes properly in Lua and C++? - c++

I have used Luabind to bind a class to Lua. I need to make sure the class is correctly disposed of when it is destructed or made null through myClass = nil.
This class adds itself to a static list inside itself like this:
template<typename T>
class component : public componentInterface
{
public:
static std::list<componentInterface *> list;
component() : componentInterface()
{
di::component<T>::list.push_back(this);
}
~component()
{
di::component<T>::list.remove(this);
}
};
And when the destructor is called it promptly removes itself from the list.

You don't have to do anything. So long as Lua is creating the object, or Lua has adopted the object, Luabind will make sure that the destructor will be called.
However, Lua is garbage collected. This means that the destructor will not necessarily be called immediately after the last reference to the object is removed. Indeed, Lua can wait essentially indefinitely, until the actual lua_State object is released.
If more immediacy is important to you, then you can do one of the following:
Have a dispose method on the object that Lua can call to destroy it early. It is therefore Lua's responsibility to not use the object after making this call.
Execute the garbage collector by calling collectgarbage, so that the garbage is collected.

Related

System.AccessViolationException error when stored callback is executed

I have passed as callback a C++ member function to a C# project through a C++/CLI wrapper (this works fine). The C# project is going to call this delegate when receiving data from another .exe process: an event will be raised and a method will call this callback. So, I needed to "save" this Action delegate using an static instance of a C# class already created. I got the following code:
// C++ unmanaged function
WRAPPER_API void dispatchEvent(std::function<void(int)> processEvent)
{
Iface::Wrapper wrapper;
wrapper.callback = &processEvent;
wrapper.PassCallback();
}
//C++ Managed
public ref class Wrapper
{
public:
std::function<void(int)>* callback;
void ReturnToCallback(int data)
{
(*callback)(data);
}
void PassCallback()
{
StartGenerator^ startGen = gcnew StartGenerator(gcnew Action<int>(this, &Wrapper::ReturnToCallback));
}
};
// C#
public class StartGenerator
{
private Communication comm;
public StartGenerator(Action<int> callback)
{
comm = Communication.Instance;
comm.callback = callback;
}
}
If I call the Action delegate in StartGenerator method, the C++ function is properly executed. However, my goal was saving the delegate to be able to call it afterwards, when data is received from another .exe process. When this data arrives, an event is raised and callback is called from the event method. It is at this point when I get the following exception:
Unhandled Exception: System.AccessViolationException: Attempted to
read or write protected memory. This is often an indication that other
memory is corrupt. at
Iface.Wrapper.ReturnToCallback(Int32 data)
I think I need to manage the lifetime of the std::function, I don't know about the lifetime of the function object being pointed to by the managed class. The object seems to be deleted and the managed class is left holding a dangling pointer.
I think I need to manage the lifetime of the std::function
Yes, I told you as much when I told you to store a pointer in the managed wrapper, here
I don't know about the lifetime of the function object being pointed to by the managed class.
The std::function is a native object and follows the native C++ rules. Putting a pointer in a managed wrapper won't make it garbage-collected.
The object seems to be deleted and the managed class is left holding a dangling pointer.
Yes, your terminology isn't exact but you've correctly diagnosed the problem. Take a look:
void dispatchEvent(std::function<void(int)> processEvent)
{
Iface::Wrapper wrapper;
wrapper.callback = &processEvent;
wrapper.PassCallback();
}
processEvent is function argument, a std::function object passed by value. The copy made and stored in the argument lives until the end of scope. It has automatic storage duration. When the function returns, all the local variables, function arguments included, are destroyed (not "deleted").
You will need to dynamically allocate (a copy of) the std::function object, like:
typedef std::function<void(int)> cbfn;
wrapper.callback = new cbfn(processEvent);
Now you have a memory leak, but at least you aren't using the object after it's destroyed. If you only make a handful of these objects the leak might even be acceptable. In general, you should implement IDisposable on your wrapper and have the Dispose method do delete callback;. In C++/CLI you use destructor syntax to accomplish that.
~Wrapper()
{
delete callback;
callback = nullptr;
}

c++ - How to implement a destructor of an object that uses itself in the constructor

I'm trying to make the Thompson's construction algorithm in c++ (I'm somewhat new to the language). But I'm having some difficulties on implementing a destructor for my class NFiniteAutomaton. In some part of the constructor of NFiniteAutomaton I have:
NFiniteAutomaton() = default;
NFiniteAutomaton(std::string regex){
// A lot of code here
// ....
NFiniteAutomaton single_ele;
single_ele.init_state = new State;
single_ele.final_state = new State;
// A lot of code here
// ....
}
Then in other parts of my code, I create pointers to single_ele.init_state's and single_ele.final_state's content in the main NFiniteAutomaton, because I want to reuse states instead of creating new ones with the same attributes.
The struct State looks like this:
struct State;
struct Transition {
State* to;
std::string symbol;
};
struct State{
std::vector<Transition> transitions;
};
So when I implement a destructor of NFiniteAutomaton that deletes all structs allocated on the heap, my problem is generated, because when single_ele gets out of the scope, it deletes all State pointers including the ones that other automata are using (because destructor gets called). One solution that I thought is to make a method Clear() that deletes all pointers whenever I want, and leave the default destructor. There is a way to implement the destructor of this class only using raw pointers?
One solution that I thought is to make a method Clear() that deletes all pointers whenever I want, and leave the default destructor.
Possible but why create a new function that the user of the class should be aware of instead of making the destructor take care of de-allocating dynamic memory? I wouldn't do that.
You should set your pointers to nullptr, before the destructor of NFiniteAutomaton is called. In the destructor use delete for init and final state.
If you want to make single_ele object persistent outside the constructor, define it as a class property rather than as a local object. The destructor can do its normal cleanup (no need for Clear() function), and the object will call the destructor only at the end of your program.
class NFIniteAutomaton {
protected:
static NFIniteAutomaton single_ele;
...
};

How to ensure Singleton is not destroyed prematurely?

In my project, I'm working with about 4 singletons made the Scott Meyer's way. One of them:
LevelRenderer& LevelRenderer::Instance()
{
static LevelRenderer obj;
return obj;
}
Now two of those Singletons, LevelRenderer and LevelSymbolTable interact with each other. For example, in this method:
void LevelRenderer::Parse(std::vector<std::string>& lineSet)
{
LevelSymbolTable& table = LevelSymbolTable::Instance();
/** removed code which was irrelevant **/
// for each line in lineSet
BOOST_FOREACH(std::string line, lineSet)
{
// for each character in the line
BOOST_FOREACH(char sym, line)
{
/** code... **/
// otherwise
else
{
sf::Sprite spr;
// Used LevelSymbolTable's Instance here...
table.GenerateSpriteFromSymbol(spr, sym);
// ^ Inside LevelRenderer
/** irrelevant code... **/
}
}
}
}
Now, although the problem hasn't occurred yet. The thing I am afraid of is, what if the LevelSymbolTable instance is already destroyed before I call GenerateSpriteFromSymbol ?
Since I used the Scott Meyer way, the Singleton's instance was allocated by the stack. Hence is is guaranteed to be destroyed using the last created first destroyed rule. Now if LevelSymbolTable's Instance is created after LevelRenderer's Instance, it will be destroyed before LevelRenderer's Instance, right? So then, if I call a method of LevelSymbolTable inside LevelRenderer (especially in LevelRenderer's destructor), I will be treading on undefined behaviour land.
As I said before, this problem hasn't actually occurred while debugging, and is purely my assumption and guess-work. So, is my conclusion correct? Is LevelSymbolTable liable to be destroyed before LevelRenderer. If so, is there any way out of this mess?
You don't have to worry about anything here.* The static keyword guarantees that it is available from when it is initialized to when the program exits. So, you can make a call to a static variable at any point after it has been initialized.
Also, you have a reference to LevelSymbolTable, not a local variable. This is what the ampersand after the class name means. So you can use it locally, but it's really "referring to" the true object which exists somewhere else. So, when the method exits, the reference will go out of scope but the object it refers to will not.
*Well, you may have to worry about one thing. In a destructor, you should just be cleaning up any memory or file references or other things of that nature you have a handle on. I don't know why you would be calling other objects in a destructor.
Define ownership relation between the objects. Either have LevelSymbolTable as member of LevelRenderer:
class LevelRenderer {
LevelSymbolTable symbolTable;
public:
static LevelRenderer& getInstance();
~LevelRenderer() { /* can use symbolTable here */ }
};
Or create one singleton Level that contains both SymbolTable and Renderer:
class Level {
SymbolTable symbolTable;
Renderer levelRenderer; // note the order here
public:
static Level& getInstance();
private:
/* have LeverRenderer save reference to symbol table,
now renderer can use symbol table anywhere */
Level() : levelRenderer(symbolTable)
{ /* ... */ }
};
EDIT: Or get rid of singletons alltogether. See why singletons are bad. I don't know the structure of your application, but from what I see, you could have Level as a normal class that knows how to render itself and has its symbol table. And have its lifetime connected to the level it is supposed to represent in the application.
Static instances will be created at the beginning of the program (before main) and cleaned up at the end (after main), and you can't rely on any particular order in which they are cleaned up. That is, if you have two instances (let's just make them globals for the sake of simplicity)
class one {
one() {}
~one() {}
};
class two {
two() {}
~two() {}
};
one the_one;
two the_other;
int main() {
...
return 0;
}
You cannot and should not make assumptions about the_one being active in the constructor or destructor of the_other. (And vice versa.)
You can, however, rely on them both being active in any other member function, and within main itself.
The scenario you raise in your question is unlikely to occur, because Parse is probably being called while the program is still active. Only when the program is about to exit would destructors be called.
In you comments, you indicate a slightly different worry, which is global destructor interdependency. This might actually occur if you have global objects that register themselves with some global container. You might expect that objects would remove themselves from the container, and that the container would eject objects.
One way to deal with this is to allow the container to take ownership of the objects that register with it. This means that what gets registered with the global container are dynamically allocated instances, rather than your Scott Meyer's singleton instances. Then, the global container would take charge of cleaning up the registered items when its global destructor is called.

Is there a way to get a C++ class to automatically execute a method just before it starts executing the destructor?

Here's a problem scenario: I've got a C++ object that includes a Cleanup() virtual method that needs to be called just before the object is destroyed. In order to do the right thing, this Cleanup method needs access to the fully-formed object (including subclass data), so I can't just call Cleanup() at the start of my own class's destructor, because by the time my class's destructor is called, the destructors any subclasses have already completed and they may have already freed some data that Cleanup() needed to look at.
The obvious solution would be to require the calling code to manually call my routine before deleting the object:
theObject->Cleanup();
delete theObject;
but that solution is fragile, since sooner or later somebody (probably me) will forget to call Cleanup() and bad things will happen.
Another solution would be to have a "holder" object that implements the pImpl technique to wrap the class, and have the holder object's destructor call Cleanup() on the object before deleting the object; but that solution isn't 100% desirable either, since it makes the class work differently from a standard C++ class and makes it impossible to allocate the object on the stack or statically.
So the question is, is there some clever technique (either in C++ or C++11) that I could use to tell the compiler to automatically call a specified (presumably virtual) method on my object before it calls the first subclass-destructor?
(come to think of it, a similar mechanism for automatically calling an Init() method -- just after the last subclass-constructor completes -- might be handy as well)
Lateral thinking: get rid of the Cleanup method, that's what a virtual destructor is for.
The very goal of a virtual destructor is to allow the outmost derived class destructor to be called when delete basepointer; is executed; and as RAII demonstrated, cleanup is the destructor's job.
Now you might argue that you would like an early Cleanup method, to ease the task of the destructor or maybe to reuse the object (kinda like a Reset method in a way). In practice, it rapidly turns into a maintenance nightmare (too easy to forget to clean one field and have state leak from one use to another).
So ask yourself the question: Why not use the destructor for what it's been created for ?
You can use a twist on the PIMPL wrapper:
class PIMPL
{
MyDataThatNeedsInitDestroy object;
public:
PIMPL(Atgs a)
: object(a)
{
object.postCreationInit();
}
~PIMP()
{
object.preDestructionDestory();
}
// All other methods are available via -> operator
MyDataThatNeedsInitDestroy* operator->() { return &object);
};
Yes, this can be done with virtual inheritance, because virtual base subobjects are always constructed (and destroyed) by the most-derived type, and the order of construction (and destruction) of base classes is well-defined also.
Of course, you also may make the delete operator private, and provide a Release() member function consisting of Cleanup(); delete this; But that wouldn't help with stack-allocated objects.
struct B
{
void cleanup()
{
if (!m_bCleanedUp)
{
m_bCleanedUp = true;
...
}
}
virtual B::~B()
{
assert(m_bCleanedUp);
...
}
bool m_bCleanedUp = false;
};
struct D : B
{
D::~D()
{
cleanup(); // if D author forgets, assert will fire
...
}
};
Is there a way to get a C++ class to automatically execute a method just before it starts executing the destructor?
You need to use smart pointer (shared_ptr - available in boost or c++11) with custom deleter instead of raw pointers.
typedef shared_ptr<MyClass> MyClassPtr;
class MyClassDeleter{
public:
void operator()(MyClass* p) const{
if (p)
p->cleanup();
delete p;
}
};
...
MyClassPtr ptr(new MyClass, MyClassDeleter());
--EDIT--
This will work for dynamically allocated objects. There is no solution (I can think of) for stack-allocated objects, so the reasonable action would be to make constructors private and make friend factory method that returns shared_ptr to constructed object - assuming you really need this mechanism.

How to handle 'this' pointer in constructor?

I have objects which create other child objects within their constructors, passing 'this' so the child can save a pointer back to its parent. I use boost::shared_ptr extensively in my programming as a safer alternative to std::auto_ptr or raw pointers. So the child would have code such as shared_ptr<Parent>, and boost provides the shared_from_this() method which the parent can give to the child.
My problem is that shared_from_this() cannot be used in a constructor, which isn't really a crime because 'this' should not be used in a constructor anyways unless you know what you're doing and don't mind the limitations.
Google's C++ Style Guide states that constructors should merely set member variables to their initial values. Any complex initialization should go in an explicit Init() method. This solves the 'this-in-constructor' problem as well as a few others as well.
What bothers me is that people using your code now must remember to call Init() every time they construct one of your objects. The only way I can think of to enforce this is by having an assertion that Init() has already been called at the top of every member function, but this is tedious to write and cumbersome to execute.
Are there any idioms out there that solve this problem at any step along the way?
Use a factory method to 2-phase construct & initialize your class, and then make the ctor & Init() function private. Then there's no way to create your object incorrectly. Just remember to keep the destructor public and to use a smart pointer:
#include <memory>
class BigObject
{
public:
static std::tr1::shared_ptr<BigObject> Create(int someParam)
{
std::tr1::shared_ptr<BigObject> ret(new BigObject(someParam));
ret->Init();
return ret;
}
private:
bool Init()
{
// do something to init
return true;
}
BigObject(int para)
{
}
BigObject() {}
};
int main()
{
std::tr1::shared_ptr<BigObject> obj = BigObject::Create(42);
return 0;
}
EDIT:
If you want to object to live on the stack, you can use a variant of the above pattern. As written this will create a temporary and use the copy ctor:
#include <memory>
class StackObject
{
public:
StackObject(const StackObject& rhs)
: n_(rhs.n_)
{
}
static StackObject Create(int val)
{
StackObject ret(val);
ret.Init();
return ret;
}
private:
int n_;
StackObject(int n = 0) : n_(n) {};
bool Init() { return true; }
};
int main()
{
StackObject sObj = StackObject::Create(42);
return 0;
}
Google's C++ programming guidelines have been criticized here and elsewhere again and again. And rightly so.
I use two-phase initialization only ever if it's hidden behind a wrapping class. If manually calling initialization functions would work, we'd still be programming in C and C++ with its constructors would never have been invented.
Depending on the situation, this may be a case where shared pointers don't add anything. They should be used anytime lifetime management is an issue. If the child objects lifetime is guaranteed to be shorter than that of the parent, I don't see a problem with using raw pointers. For instance, if the parent creates and deletes the child objects (and no one else does), there is no question over who should delete the child objects.
KeithB has a really good point that I would like to extend (in a sense that is not related to the question, but that will not fit in a comment):
In the specific case of the relation of an object with its subobjects the lifetimes are guaranteed: the parent object will always outlive the child object. In this case the child (member) object does not share the ownership of the parent (containing) object, and a shared_ptr should not be used. It should not be used for semantic reasons (no shared ownership at all) nor for practical reasons: you can introduce all sorts of problems: memory leaks and incorrect deletions.
To ease discussion I will use P to refer to the parent object and C to refer to the child or contained object.
If P lifetime is externally handled with a shared_ptr, then adding another shared_ptr in C to refer to P will have the effect of creating a cycle. Once you have a cycle in memory managed by reference counting you most probably have a memory leak: when the last external shared_ptr that refers to P goes out of scope, the pointer in C is still alive, so the reference count for P does not reach 0 and the object is not released, even if it is no longer accessible.
If P is handled by a different pointer then when the pointer gets deleted it will call the P destructor, that will cascade into calling the C destructor. The reference count for P in the shared_ptr that C has will reach 0 and it will trigger a double deletion.
If P has automatic storage duration, when it's destructor gets called (the object goes out of scope or the containing object destructor is called) then the shared_ptr will trigger the deletion of a block of memory that was not new-ed.
The common solution is breaking cycles with weak_ptrs, so that the child object would not keep a shared_ptr to the parent, but rather a weak_ptr. At this stage the problem is the same: to create a weak_ptr the object must already be managed by a shared_ptr, which during construction cannot happen.
Consider using either a raw pointer (handling ownership of a resource through a pointer is unsafe, but here ownership is handled externally so that is not an issue) or even a reference (which also is telling other programmers that you trust the referred object P to outlive the referring object C)
A object that requires complex construction sounds like a job for a factory.
Define an interface or an abstract class, one that cannot be constructed, plus a free-function that, possibly with parameters, returns a pointer to the interface, but behinds the scenes takes care of the complexity.
You have to think of design in terms of what the end user of your class has to do.
Do you really need to use the shared_ptr in this case? Can the child just have a pointer? After all, it's the child object, so it's owned by the parent, so couldn't it just have a normal pointer to it's parent?