I’m working on a C++ API which exports several classes from a DLL.
A public class interface should follow the following conventions:
- All functions return an error code.
- Output parameters are used for additional return values.
- Pass by pointer is used for Output parameters.
- Pass by const reference is used for Input parameters (pass by value for primitive types).
- When the client should take ownership of output parameter
shared_ptris 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_ptrin any sane way… this can lead to problems later. Andshared_ptrreally means unspecified or shared ownership of the underlying resource.I typically document the function and use something like:
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.
or
or
etc.
Note that this can be made neater if you change your function definition to: