One fundamental difference between outdated C/C++ code and Modern C++ code, is that one is still stuck in memory management, and the other is instead memory managed, in the powerful grip of the STL phenomena. Another problem is that “C/C++” has been a misnomer for some time, more than a decade – and yet it persists in the shadow of Modern C++. C/C++ is the past, Modern C++ and Future C++ is here to stay and rapidly approaching — the mere phrase C/C++ will soon be left to ancient C++ history.
When going about managing memory in C/C++, you might consider using new/delete somehow. In C++, new/delete paradigm is the last one referenced and generally only for backward compatibility. new/delete has been entirely replaced by STL concepts and is used almost exclusively in either particular advanced code or particularly obsolete code. In the case where your code is obsolete, the solution is an STL container such as std::string, std::shared_ptr, std::span, or std::vector.
When the shift to STL happens, we get a lot of change. Memory Management becomes Memory Managed; algorithms, parallel capabilities, and expertly produced and maintained code, become available. Entire programming paradigm shifts occur, and “C/C++” writers become Modern and Future C++ writers.
In this code example, we demonstrate memory managed.
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
#include <numeric>
#include <span>
#include <format>
#include <sstream>
int main() {
//your first choice should be to use an
// STL container to manage its own memory
std::vector<int> ivec(10, 0);
std::shared_ptr<std::string> msg =
std::make_shared<std::string>("Hello World");
//and then proceed to use
// STL algorithms and STL containers
std::iota(ivec.begin(), ivec.end(), 0);
auto join = [&]() -> std::string {
std::ostringstream oss;
for (const auto& item : ivec)
oss << item << ", ";
return oss.str();
};
//if you must interact with C/C++ style code,
// you may use new/delete in some cases
// but this is not recommended
constexpr auto size = 5;
int* iptr = new int[size](1,2,3,4,5);
//you are still empowered by the STL algorithms
std::span<int> ispan(iptr, size);
int csum = std::reduce(ispan.begin(), ispan.end(), 0);
delete[] iptr;
*msg = std::format("{}. We have figured out: {}"
"and the following: {}, "
"contributing to the "
"STL phenomena"
"\nno memory leaks"
, *msg, join(), csum);
std::cout << *msg;
std::puts("\nprogram finished\nPress enter");
std::cin.get();
return 0;
}