AUTOSAR C++14 Rule A15-1-4
If a function exits with an exception, then before a throw, the function shall place all objects/resources that the function constructed in valid states or it shall delete them.
Since R2021b
Description
Rule Definition
If a function exits with an exception, then before a throw, the function shall place all objects/resources that the function constructed in valid states or it shall delete them.
Rationale
When a function exits with an exception, any resource or memory that the function allocated might not be properly deallocated. Consider this code:
FILE* FilePtr; //... void foo(){ FilePtr = fopen("some_file.txt", "r"); //... if(/*error condition*/) throw ERROR_CODE; delete FilePtr; }
FilePtr
before the
throw
statement.Instead of manually tracking the allocation and deallocation of resources, the best practice is to follow the "Resource Acquisition Is Initialization" (RAII) or the "Constructor Acquires, Destructor Releases" (CADre) design pattern. In this pattern, resource allocation is performed in constructors and resource deallocation is performed in destructors. The lifecycle of resources are controlled by scope-bound objects in this pattern. When functions reach the end of their scope, the acquired resources are properly released. Consider this code:
void releaseFile(std::FILE* fp) { std::fclose(fp); } std::unique_ptr<std::FILE, decltype(&releaseFile)> FilePtr; //... void foo(){ FilePtr(std::fopen("some_file.txt"),&releaseFile); //... if(/*error condition*/) throw ERROR_CODE; }
FilePTR
invokes the function
releaseFile
to delete the allocated resource once the function
foo
reaches the end of its scope, whether normally or because of an
unhandled exception.C++ smart pointers such as std::unique_ptr
and
std::shared_ptr
follow the RAII pattern. They simplify managing the
lifecycle of resources during exception handling. Avoid using raw pointers whenever
possible.
Polyspace Implementation
Polyspace® flags an uncaught throw
statement in a
if the statement might result in resource
leak. For instance,
A
throw
statement outside atry
block is flagged if the allocated resources are not deallocated before the statement.A
throw
statement in acatch
block is flagged if the resources are not deallocated before raising the exception.
Polyspace does not flag a throw
statement if it is within a
try
block that has an appropriate handler or if the exception is raised
before allocating resources.
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Version History
Introduced in R2021b