Mastering memory efficiency with std::span
A useful C++20 tool for providing a non-owning view of contiguous memory
Before diving into the usage of std::span
, it is important to understand the concept of ownership of resources. When a container such as a std::vector
is created, the container has ownership of the memory used to store data inside of it, meaning that it is the responsibility of the container to manage the lifecycle of this memory. Let’s look at a few common scenarios where a std::vector
is used and determine if the ownership is affected:
- Viewing data in a container:
int main() {
std::vector<int> myVector{1, 2, 3};
for (const auto& value : myVector) {
std::cout << value << " ";
}
std::cout << std::endl;
}
// Output:
// 1 2 3
In this example, a range-based for
loop is used to iterate over myVector
in the main
function. Here, myVector
has ownership of the memory used to store the data — The creation of the std::vector
allocated memory, which will be deallocated when main
exits. Iterating over myVector
doesn’t affect ownership of the container.
const auto&
is used within the for
loop for improved efficiency and best practices — const
indicates that value
should not be modified, auto
lets the compiler deduce the type, and the &
symbol turns value
into a reference instead of an unnecessary copy of data.
- Passing a container by value:
int…