Last active
June 11, 2022 18:35
-
-
Save saxbophone/eb0af153f1dfb4f6dc52f7d23ed0b507 to your computer and use it in GitHub Desktop.
Using std::span<> to "babysit" a heap-allocated array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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