Before boost::shared_ptr, was it considered a bad practice to return a heap allocated pointer from a function, since the caller will be required to remember to free() that object?
Or, was it considered “normal”?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I don’t consider it bad practice, so long as your API also provides an equivalent
XXX_free(orXXX_close,XXX_clearup, or whatever) function, that the client code can call when finished with the pointer.That way, you have a consistent, symmetrical API, in the sense that responsibility for the lifetime of a heap object is maintained in one place.
This approach is also amenable to more-complex resource freeing. For example, if the pointer that gets returned is to a dynamically-allocated struct that in turn has members that point to dynamically-allocated memory, the entire cleanup procedure can be hidden/abstracted from the client code.