I'm working on a C++ API which exports several classes from a DLL.
A public class interface should follow the following conventions:
shared_ptr
is used, otherwise a normal pointer.Example interface:
typedef std::shared_ptr<Object> ObjectPtr;
class APIClass
{
ErrorCode SetSomething(int i);
ErrorCode IsSomethingSet(bool* ask);
ErrorCode DoSomething();
ErrorCode GetSomething(ObjectPtr* outObj);
}
Example usage:
ErrorCode res;
ObjectPtr obj;
res = myApiClass->GetSomething(&obj);
GetSomething implementation:
ErrorCode APIClass::GetSomething(ObjectPtr* outObj)
{
ObjectPtr temp(new Object(), CleanUpFunction<Object>);
// Do something with object temp.
...
*outObj= temp;
return OK;
}
Is it save to use a shared_ptr in this way or are there possible issues I should be aware of?
This is fine, but I'd ask whether a shared pointer is really necessary in this case. Mostly because you can't release a pointer from a shared_ptr
in any sane way... this can lead to problems later. And shared_ptr
really means unspecified or shared ownership of the underlying resource.
I typically document the function and use something like:
// Caller must delete the outObj once done.
ErrorCode APIClass::GetSomething( Object* & outObj )
{
// I use auto_ptr so I can release it later...
// Mostly I hate auto_ptr, but for this its invaluable.
auto_ptr<Object> obj( new Object );
...
outObj = obj.release();
return OK;
}
This way it is up to the client what they want to store the pointer into, and it is clear that ownership of the object passes to the caller.
Client code can then use an appropriate container.
Object * obj_raw;
ErrorCode ec = apiClass.GetSomething( obj_raw )
if( ec!=OK ) { .. do something with ec .. }
shared_ptr<Object> obj( obj_raw );
or
auto_ptr<Object> obj( obj_raw );
or
scoped_ptr<Object> obj( obj_raw);
etc.
Note that this can be made neater if you change your function definition to:
// Caller must delete the return value.
// On error, NULL is returned and e filled in appropriately.
Object* APIClass::GetSomething( ErrorCode & e )
{
auto_ptr<Object> obj( new Object );
..
e = OK;
return obj.release();
}
//Now using it looks like this:
ErrorCode ec;
shared_ptr<Object> obj( apiObject.GetSomething(ec) );
if(!obj)
{
.. do something with ec ..
}