On Wednesday, September 11, 2019 at 5:04:43 AM UTC-4, Juha Nieminen wrote:
For a stateful allocator, you need to pass an instance of the constructor
to the object. But MyAlloc also isn't right, it needs to be a template class,
and have a constructor that supports rebinding. As a minimal example, try
#include <iostream>
#include <string>
#include <memory>
template <class T>
struct MyAlloc
{
using value_type = T;
using size_type = std::size_t;
using propagate_on_container_move_assignment = std::true_type;
MyAlloc(int) {}
template< class U >
MyAlloc(const MyAlloc<U>&) noexcept {}
T* allocate(size_type n)
{
return static_cast<T*>(::operator new(n * sizeof(T)));
}
void deallocate(T* ptr, size_type) noexcept
{
::operator delete(ptr);
}
bool operator==(const MyAlloc&) const { return true; }
bool operator!=(const MyAlloc&) const { return false; }
};
int main()
{
std::basic_string<char, std::char_traits<char>, MyAlloc<char>> str("hello", MyAlloc<char>(1));
std::cout << str << "\n";
}