Rule A18-5-8 (required, implementation, partially automated)
Objects that do not outlive a function shall have automatic storage duration.
Rationale
Creating objects with automatic storage duration implies that there is no additional allocation and deallocation cost, which would occur when using dynamic storage. Note: This rule applies only to objects created in a function scope, it does not forbid the object to internally allocate additional memory on heap.
Exception
Objects causing high memory utilization may be allocated on heap using memory managing objects.
Example
//% $Id: A18-5-8.cpp 311792 2018-03-15 04:15:08Z christof.meerwald $
#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);
}
See also
C++ Core Guidelines [11]: R.5: Prefer scoped objects, don’t heap-allocate unnecessarily.