Tuesday, 3 September 2013

API Memory: Heap or Stack? (C++)

API Memory: Heap or Stack? (C++)

Context: I'm making a simple library. In it, I'm returning one of the
classes I've created, which I could, a) declare on the stack and expect
the user to copy to the heap if it needs to be on the heap, or, b) declare
on the heap and expect the user to delete the object when they're done
with it.
Which of these methods is a best practice, and if there isn't a clear
winner, which should be used where? I'm thinking I'll create a .dll (.so,
etc), but would the answer change if I were creating a different type of
binary? What would happen if a user copied the headers and sources into
their project and built the entire library each time they build their
project. What would change?
Side note: I suppose a third option would be to allow a parameter to
signify whether or not an object returned by a function is on the stack.
This seems really convoluted, though, and I've never seen a library/API do
that. A fourth option would be to allow a pointer to an already-existing
object, which is then filled with new data. This way allows for the user
to specify which sort of object they'd like, but it, again, seems rather
convoluted.

No comments:

Post a Comment