Delete or virtual delete?
I am writing a lib and a demo project. The project doesn't care what version of lib I am using (I can use sdl, directx or whatever I like as the gfx backend). To get an object, I do
Obj *obj = libname_newDevice();
Now, should I use delete or should I do obj->deleteMe();
? I am asking because I am not doing anything new, so I shouldn't be doing the deletion?
I have obj->create(theType);
one that returns a class with an Obj interface. My real question is, do I need it libname_deleteDevice();
or is it obj->deleteMe()
great, since I have deleteMe in the interface?
I would take one more step.
If you are using a factory function to create, it might make sense to use a factory function to destroy. In addition to this, to make it all a pleasant and safe investment in the facility.
class ObjWrap
{
public:
ObjWrap()
:obj(libname_newDevice())
{}
~ObjWrap()
{ libname_deleteDevice(obj);}
private:
ObjWrap(ObjWrap const&); // Dont copy
void operator=(ObjWrap const&); // Dont copy
Obj* obj;
}; // If you want to copy then you need to extra work on ref counting
// This may need some form of smart pointer.
source to share
Please try to clarify your question. This is completely incomprehensible to me.
- Why are you talking about graphic back end? Does this relate to the question?
- Are you asking how should you design your library or how to use it?
It is good practice to create a factory to create the object. I guess this is the role libname_newDevice()
.
The library should also provide a way to delete an object (for example, obj->DeleteMe()
or libname_Delete(obj)
).
Don't rely on C ++ delete
: the caller and the library can be compiled with a different version of the compiler, which will do different things related to memory and resource allocation. Therefore, it is safer if your library removes the object it created.
source to share
I think the best way is to read RAII and have some sort of reference counting wrapper object (you can even use a shared_ptr with a custom liberator).
source to share