0

I have started experimenting using custom allocators with std::basic_string in a video game project. This is my first time dealing with custom allocators, so I'm learning a lot.

But the problem is, I would like to be able to call any function taking a "string" parameter with any std::basic_string (std::string, std::basic_string<char, std::char_traits<char>, custom_allocator<char>, etc.).

However, providing a custom allocator "changes" the type of std::basic_string (I mean, it differs from std::string that I've been using).

So I thought of different solutions:

  • Use template programming in functions to take a T instead... but using templates everywhere seems a bit tedious and overkill...
  • Switch to C-style strings everywhere, and provide my_string.c_str(), which seems like a very bad idea, considering the loss of C++ features.
  • Implement my own String base class and make all the CustomAllocatedString inherit from it. This is for a personal project, so I don't mind experimenting, but I know that implementing my own "STL" can be very time consuming (among other things).
  • During my research, I learned about polymorphic allocators and std::pmr::string (I use C++ 17). Although this seems to include memory overhead (plus the indirection), it's really interesting.
  • Am I missing something really obvious here?

What do you think about this? Or is mixing different allocation methods with a single type a really bad idea in the end?

1 Answers1

2

The solution might be to use string_view instead; that way functions don't have to deal with how strings are allocated.

#include <iostream>
#include <string>
#include <string_view>

void foo(const std::string_view str) 
{ 
    std::cout << str; 
}

int main() 
{
    std::string s = "Hello";
    std::pmr::string s2 = "World";
    foo(s);
    foo(" ");
    foo(s2);
    foo("\n");
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93