in C++, suppose there is a method in a Helper class which returns me a pointer to another object. I don’t have any more information about this method except the method signature and the type of returned object. How to do memory management in this case?
I attempted to use smart pointer as this function below:
void f() {
auto_ptr<SomeClass> p_someClass = p_Helper->getSomeclass();
p_someClass->doSomething();
}
The memory allocated to p_someClass is deallocated as soon as f() goes out of scope.
However, what if getSomeclass() doesn’t allocate new memory but simply return a “singleton” pointer (and p_Helper is also singleton)? Then the next call to p_Helper->getSomeclass() will be in trouble.
What is the usual way to handle this issue, esp when there is very little documentation on the Helper class?
What does the documentation of the helper class say? That is the
ultimate issue. You can’t return a pointer or a reference without
specifying its lifetime: if it’s a pointer to something internal in the
class, it might be the lifetime of the class object, but it could also
have static lifetime (until the end of the program—this is the
case of functions which return string literals as
char const*), itmight have some shorter lifetime (e.g. references returned by
operator[]by the standard library containers), or the helper mightexpect you to delete it. The latter should be rare, however, in pure
C++; the convention in such cases is to return
std::auto_ptr(orstd::unique_ptrif you have a very modern compiler). (In C, it wasfrequent to document that the returned pointer had to be freed by
calling a specific function in the library which returned it. Without
destructors, you have to do something to regain control at the end.)
In the absense of documentation, I’m tempted to say that the library is
not usable. Still… supposing that it points to something internal and
has the lifetime of the class is probably the most reasonable guess;
it’s the case which programmers most easily forget to document.
Deleting it, or putting it in a smart pointer which will delete it, is
probably not a good idea: enough has been said about ownership issues
that it seems unlikely that a class author would fail to document the
fact if you were supposed to delete it. (Note, however, that the
lifetime issues remain even if you’re not supposed to delete it.)