Last active
May 26, 2025 07:28
-
-
Save andreysolovyev381/66299b58e768528d3c5964f925a45e0c to your computer and use it in GitHub Desktop.
std:: vs std::pmr:: addresses
This file contains hidden or 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 <iostream> | |
#include <memory_resource> | |
#include <unordered_map> | |
#include <string> | |
#include <vector> | |
void print_string_info(const std::string& str, const std::string& name, const void* buffer_start, const void* buffer_end) { | |
std::cout << name << " address: " << reinterpret_cast<uintptr_t>(str.data()) << std::endl; | |
bool in_buffer = (void*)str.data() >= buffer_start && (void*)str.data() < buffer_end; | |
std::cout << name << " in buffer: " << (in_buffer ? "Yes" : "No") << std::endl; | |
} | |
void print_pmr_string_info(const std::pmr::string& str, const std::string& name, const void* buffer_start, const void* buffer_end) { | |
std::cout << name << " address: " << reinterpret_cast<uintptr_t>(str.data()) << std::endl; | |
bool in_buffer = (void*)str.data() >= buffer_start && (void*)str.data() < buffer_end; | |
std::cout << name << " in buffer: " << (in_buffer ? "Yes" : "No") << std::endl; | |
} | |
int main() { | |
std::vector<char> buffer(1024); // Buffer for monotonic resource | |
std::pmr::monotonic_buffer_resource resource(buffer.data(), buffer.size()); | |
std::cout << "=== Using std::string as key ===\n"; | |
std::pmr::unordered_map<std::string, int> map(&resource); | |
map.emplace("long_key_string_1234567890", 42); // Long string to avoid SSO | |
print_string_info(map.cbegin()->first, "std::string key", buffer.data(), buffer.data() + buffer.size()); | |
std::cout << "\n=== Using std::pmr::string as key ===\n"; | |
std::pmr::unordered_map<std::pmr::string, int> pmr_map(&resource); | |
pmr_map.emplace("long_key_string_1234567890", 43); // Long string for consistency | |
print_pmr_string_info(pmr_map.cbegin()->first, "std::pmr::string key", buffer.data(), buffer.data() + buffer.size()); | |
std::cout << "\nMonotonic buffer range: " << reinterpret_cast<uintptr_t>(buffer.data()) | |
<< " to " << reinterpret_cast<uintptr_t>(buffer.data() + buffer.size()) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment