The difference between placement new operator and pmr in memory_resource?

418 views Asked by At

In C++17 you can have a code like this:

char buffer[64] = {}; 
std::pmr::monotonic_buffer_resource 
     pool{std::data(buffer), std::size(buffer)};
std::pmr::vector<char> vec{ &pool };

We also have

char buf[64];
std::vector<char> *vect = new (buf) std::vector<char>;    // placement new

Both of the codes use some space in the stack. To me, it seems that new placement is excessive while memory_rsource can do much more. It was just an example on the stack but even if you want to have memory in the heap pmr will handle more conditions.

Is it an excessive definition in the standard? If I need to have a memory pool which one should I use? Which one handles exceptions better.

I have not found good tutorials on memory_resources and lots of stuff is ambiguous for me. Moreover placement new can not do much.

1

There are 1 answers

3
Nicol Bolas On

Is it an excessive definition in the standard?

No. It's the inevitable result of comparing a high-level tool to a low-level tool. Obviously, the high-level tool will use the low-level one.

Without placement-new (or equivalents like C++20's std::construct_at), it would be impossible to create objects within existing storage. That is, polymorphic_allocator will use placement-new (or an equivalent) internally.

It should also be noted that std::memory_resource is merely the way to allocate memory. Placement-new is how you create objects within accessible memory. They do completely different and unrelated things. This is why I said that it is polymorphic_allocator, not the memory_resource or any derived class, that uses placement-new.

memory_resources are pure memory allocators, not object construction mechanisms. Container allocators combine object construction with memory allocation. As such, comparing