I want to write a library with \"no resource leak guarantee\" feature. So I shal
ID: 659061 • Letter: I
Question
I want to write a library with "no resource leak guarantee" feature. So I shall know whether each method allocates any resource or not. It may change the code. For example:
void foo()
{
methodDontAllocateAnyResources();
methodCanThrow();
}
void bar()
methodAllocateSomeResources();
try{
methodCanThrow();
}
catch(const std::exception& exp){
releaseAllocatedResources();
throw;
}
}
Both foo() and bar() functions can throw an exception. It doesn't matter because I let exceptions to propagate. But In bar(), I must catch a possible exception to avoid a resource leak.
In the example I could decide to use or not a try-catch block easily. However, you know, normally we cannot understand whether a method allocates any resource or not by its name. So, I've decided to put this information into method documentation. Doxygen doesn't have such a tag. Also, I cannot find any web resources suggest that. Do you think using a custom @resource-allocation tag is a good idea?
Thanks
Explanation / Answer
I want to write a library with "no resource leak guarantee" feature. [...] It doesn't matter because I let exceptions to propagate. But In bar(), I must catch a possible exception to avoid a resource leak.
This sounds good, all the way to the last sentence.
Consider using RAII resources and smarter return types to manage resources, instead of internal try/catch blocks.
Alternative implementation for bar:
struct raii_resource {
{
raii_resource(type value) : value_{value} {}
~raii_resource() { releaseAllocatedResources(value_); }
type value_;
};
void bar() {
raii_resource r = methodAllocateSomeResources(); // returns type instance
methodCanThrow();
}
If your function needs to return the allocated resource to the client code, simply wrap the return value in a smart wrapper (that will delete it at the end of scope).
Usually, in C++ you should only use try/catch blocks to handle errors, not to release allocated resources.
If you do this (use raii), the documentation of allocated resources will become irrelevant, because resource leaks are no longer possible.
That said, to add allocations information to the API documentation, I would add it as a @remarks or something similar.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.