Skip to content

Instantly share code, notes, and snippets.

@saxbophone
Last active June 11, 2022 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saxbophone/eb0af153f1dfb4f6dc52f7d23ed0b507 to your computer and use it in GitHub Desktop.
Save saxbophone/eb0af153f1dfb4f6dc52f7d23ed0b507 to your computer and use it in GitHub Desktop.
Using std::span<> to "babysit" a heap-allocated array
#include <cstddef>
#include <span>
std::span<int> allocate(std::size_t size) {
int* storage = new int[size];
return std::span<int>{storage, size};
}
void deallocate(std::span<int>& items) {
delete[] items.data();
items = {};
}
#include <iostream>
int main() {
auto items = allocate(12);
for (std::size_t i = 0; i < items.size(); i++) {
std::cout << items[i] << " ";
items[i] = i;
}
std::cout << std::endl;
for (std::size_t i = 0; i < items.size(); i++) {
std::cout << items[i] << " ";
}
std::cout << std::endl;
deallocate(items);
for (std::size_t i = 0; i < items.size(); i++) {
std::cout << items[i] << " ";
}
std::cout << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment