...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <iostream> #include <vector> void f(const std::vector<int> &Cc) { for (auto Ii = Cc.begin(), Ee = Ii + 20; Ii != Ee; ++Ii) { std::cout << *Ii << std::endl; } } |
Compliant Solution (std::vector)
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <algorithm> #include <vector> void f(const std::vector<int> &Cc) { const std::vector<int>::size_type MaxSizemaxSize = 20; for (auto Ii = Cc.begin(), Ee = Ii + std::min(MaxSizemaxSize, Cc.size()); Ii != Ee; ++Ii) { // ... } } |
This compliant solution also uses a named constant value in compliance with DCL06-CPP. Use meaningful symbolic constants to represent literal values in program logic.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <cstddef> void f(const char *buf, std::size_t len) { // Check for overflow if (buf + len < buf) { len = -(std::size_t)buf - 1; } } |
This code resembles the test for wraparound from the sprint() function as implemented for the Plan 9 operating system. If buf + len < buf evaluates to true, len is assigned the remaining space minus one byte. However, because the expression buf + len < buf constitutes undefined behavior, compilers can assume this condition will never occur and optimize away the entire conditional statement.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <cstdint> void f(const char *buf, std::size_t len) { // Check for overflow auto bint = reinterpret_cast<std::uintptr_t>(buf); if (bint + len < bint) { len = -(std::size_t)bint - 1; } } |
This compliant solution works on architectures that provide a linear address space. Some word-oriented machines are likely to produce a word address with the high-order bits used as a byte selector, in which case this solution will fail. Consequently, this solution is not portable.
...