AutosarC++17_10-A18.5.8¶
Objects that do not outlive a function shall have automatic storage duration
Required inputs: IR, StaticSemanticAnalysis
| Level | required |
|---|---|
| Target | implementation |
| Enforcement | partially automated |
Rationale
Allocating local objects on stack implies that there is no additional allocation and deallocation cost, which would occur when using memory managing objects.
Note: This rule applies only to objects created in a scope, it does not forbid this object to internally allocate memory on heap.
Exceptions
Objects causing high memory utilization may be allocated on heap using memory managing objects.
Example
//% $Id: A18-5-8.cpp 289816 2017-10-06 11:19:42Z michal.szczepankiewicz $
#include <cstdint>
#include <memory>
#include <vector>
class StackBitmap {
public:
constexpr static size_t maxSize = 65535;
using BitmapRawType = std::array<uint8_t, maxSize>;
StackBitmap(const std::string &path, uint32_t bitmapSize) {
// read bitmapSize bytes from the file path
}
const BitmapRawType &GetBitmap() const noexcept { return bmp; }
private:
BitmapRawType bmp;
};
void AddWidgetToLayout(int32_t row, int32_t col) {
auto idx = std::make_pair(row, col); // Compliant
auto spIdx =
std::make_shared<std::pair<int32_t, int32_t>>(row, col); // Non-compliant
// addWidget to index idx
}
uint8_t CalcAverageBitmapColor(const std::string &path, uint32_t bitmapSize) {
std::vector<uint8_t> bmp1(bitmapSize); // Compliant
// read bitmap from path
StackBitmap bmp2(path, bitmapSize); // Non-compliant
bmp2.GetBitmap();
}
int main(int, char **) {
AddWidgetToLayout(5, 8);
CalcAverageBitmapColor("path/to/bitmap.bmp", 32000);
return 0;
}
See Also
- C++ Core Guidelines [10]: R.5: Prefer scoped objects, don’t heap-allocate unnecessarily. ——————————————————————————
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
could_be_scoped |
Local objects shall be allocated on the stack. |
None |
False |
Options¶
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
allow_smart_ptr_from_function_return¶
allow_smart_ptr_from_function_return : bool = True
std::make_{shared,unique,..} will remain a violation.
consider_exceptional_exit¶
consider_exceptional_exit : bool = False
ignore_arrays¶
ignore_arrays : bool = False