AutosarC++17_10-A18.5.8

Objects that do not outlive a function shall have automatic storage duration

Required inputs: IR, StaticSemanticAnalysis

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

allow_smart_ptr_from_function_return

allow_smart_ptr_from_function_return : bool = True

Whether to allow a smart pointer returned from a function as a local variable in a function. Calling the smart pointer constructors or the helper functions std::make_{shared,unique,..} will remain a violation.
 

consider_exceptional_exit

consider_exceptional_exit : bool = False

Whether leaving a function due to an exception should be considered as an exit, i.e., if objects that have not been deallocated on the path to the exceptional exit should be reported.
 

ignore_arrays

ignore_arrays : bool = False

Whether to ignore objects allocated using array new.