-
Notifications
You must be signed in to change notification settings - Fork 74
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[330] - Did you know that C++17 added std::pmr::polymorphic_allocator?
- Loading branch information
1 parent
83039db
commit 7988623
Showing
3 changed files
with
130 additions
and
0 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
<details open><summary>Info</summary><p> | ||
|
||
* **Did you know that C++17 added std::pmr::polymorphic_allocator?** | ||
|
||
* https://eel.is/c++draft/mem.res.syn#header:%3cmemory_resource | ||
|
||
</p></details><details open><summary>Example</summary><p> | ||
|
||
```cpp | ||
#include <memory_resource> | ||
#include <cassert> | ||
|
||
int main() { | ||
// Create a memory resource | ||
std::pmr::monotonic_buffer_resource resource(1024); | ||
|
||
// Create a polymorphic allocator using the memory resource | ||
std::pmr::polymorphic_allocator<int> allocator(&resource); | ||
|
||
// Allocate memory for an array of 10 integers using the polymorphic allocator | ||
int* ptr = allocator.allocate(10); | ||
|
||
// Test that the allocation was successful | ||
assert(ptr); | ||
|
||
// Deallocate the memory | ||
allocator.deallocate(ptr, 10); | ||
} | ||
``` | ||
|
||
> https://godbolt.org/z/1h7voEGo6 | ||
</p></details><details open><summary>Puzzle</summary><p> | ||
|
||
* **Can you create pmr::vector which will use pmr::monotonic_buffer_resource/pmr::polymorphic_allocator?** | ||
|
||
```cpp | ||
#include <memory_resource> | ||
#include <vector> | ||
|
||
int main() { | ||
using namespace boost::ut; | ||
std::array<char, 1024> buffer{}; | ||
|
||
"pmr"_test = [&buffer] { | ||
std::pmr::vector<char> vec{}; // TODO | ||
|
||
vec.push_back('a'); | ||
vec.push_back('b'); | ||
vec.push_back('c'); | ||
|
||
expect(vec[0] == 'a' and vec[1] == 'b' and vec[2] == 'c'); | ||
expect(std::string_view(buffer.data(), buffer.size()).contains("abc")); | ||
}; | ||
} | ||
``` | ||
|
||
> https://godbolt.org/z/o1hx1fdEn | ||
</p></details><details><summary>Solutions</summary><p> | ||
</p></details> |