Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API return type -- Force a smart pointer onto the user?

Tags:

c++

pointers

Suppose I have an API-border function that creates and returns an object:

<?> createOneObject();

What would be the best way to return the object to the caller?

  • Return the raw MyObject* and let the caller handle the pointer herself
  • Return std::shared_ptr<MyObject>
  • Something else?
like image 314
stulleman Avatar asked Dec 08 '25 14:12

stulleman


1 Answers

Depends.

In general, returning a raw pointer is bad, because the type itself does not communicate ownership. Should the user delete the pointer? If yes, then how? If not, then when does the library do it? How does the user know if the pointer is still valid? Those things have to be documented, and lazy programmers might skip reading the docs. But, if your API must be callable from C or other languages, then a raw pointer may be the only option.

Shared pointer might be useful in special cases, but they do have overhead. If you don't need shared ownership, then use of a shared pointer may be overkill.

Unique pointer is what I would use unless there is specific reason to use something else.

Although, that assumes that a pointer should be returned in the first place. Another great option could be to return an object.

To be a bit more concrete: I have a player class that just stores an id and just offers lots of methods. In this case you would prefer to return by value?

Most definitely.

like image 92
eerorika Avatar answered Dec 10 '25 03:12

eerorika