PMR showcase
This code showcases manageing memory using pmrunknown
plain_text
a year ago
1.6 kB
15
Indexable
#include <ios>
#include <memory_resource>
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
class SongList {
public:
SongList()
: buffer{},
mem_resource(buffer, sizeof(buffer), std::pmr::null_memory_resource()),
songs(&mem_resource)
{
}
void addSong(const std::string& name) {
songs.emplace_back(name);
}
const std::pmr::vector<std::pmr::string>& getSongs() const {
return songs;
}
void printBuffer() const {
std::cout << "buffer address: " << std::hex << static_cast<const void*>(buffer) << std::endl;
for (const auto& song : songs) {
std::cout << "Song: " << song << ", address: " << static_cast<const void*>(song.data()) << std::endl;
}
}
private:
// Increase buffer size to better fit vector and string allocations
char buffer[200];
std::pmr::monotonic_buffer_resource mem_resource;
std::pmr::vector<std::pmr::string> songs;
};
int main() {
SongList songList;
songList.addSong("Song A");
songList.addSong("Song B");
const auto& songs = songList.getSongs();
std::cout << "Song list:" << std::endl;
for (const auto& song : songs) {
// Output the song namces
// In a real application, you might print them or process them further
std::cout << song << std::endl;
}
// Print buffer and song addresses for allocation check
std::cout << "Buffer context:" << std::endl;
songList.printBuffer();
return 0;
} Editor is loading...
Leave a Comment