Question

I am writing a lib and a demo project. The project doesn't care which version of the lib I use (I can use sdl, directx or whatever I like as the gfx backend). To get the object I do

Obj *obj = libname_newDevice();

Now, should I use delete or should I do obj->deleteMe();? I ask because I am not exactly doing new so I shouldn't be doing the delete?

I have obj->create(theType); which returns a class with the Obj interface. My real question is do I need a libname_deleteDevice(); or is obj->deleteMe() fine since I have a deleteMe in the interface?

Was it helpful?

Solution

I would take one step further.
If you are using a factory function to create, it may be logical to use a factory function to destroy. In addition to this to make it all nice and exetion safe wrap in in an object.

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.

OTHER TIPS

Since you are abstracting the creation inside libname_newDevice() (which I have to say isn't a good approach), you should destroy using something like libname_destroyDevice (obj).

And as the comment from Martin suggests, it's best to put them in the constructor and destructor of a custom class, that you just need to create on stack, and the compiler will take care of the rest.

Please try to clarify your question. It's totally unclear to me.

  • Why do you speak of a graphical back end? Is it relevant to the question?
  • Are you asking how you should design your library or how you should use it?

It's good practice to have an object factory to create the object. I assume this is the role of libname_newDevice().

The library should also provide a way to delete the object (such as obj->DeleteMe() or libname_Delete(obj) ).

Don't rely on C++'s delete: caller and library might have been compiled with different version of the compiler, which would do different things regarding memory and resources allocation. It's therefore safer if your lib deletes the object it created.

I think the best way would be to honor RAII and have some reference counting wrapper object (you can even use shared_ptr with a custom deallocator).

You definitely don't want to implement Obj::deleteMe(). It would have to do something like:

delete this;

while you were still inside this->deleteMe(). Follow Jaywalker's suggestion and make the destroy function take an Obj* as a parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top