Link std :: basic_string specializing a string with a custom allocator as a constant std :: string object without overhead?

Given an object of class std::basic_string<char, std::char_traits<char>,my_allocator<char> > , how do you pass it to a third-party function that expects a constant reference to an object of class std::string without any copies?

I think that if we take a stateless allocator, then theoretically the two types should be exactly the same at run time. Therefore, you can simply repeat the type interpretation, for example:

 // my_allocator template is some place else... typedef std::basic_string< char, std::char_traits<char>, my_allocator<char> > my_string; void third_party_foo(const std::string &s); int main() { const my_string str = "Hello, world!"; third_party_foo(*(const std::string *)&str); } 

Given a dispenser that has a state (which we can have with C ++ 11), I would suggest that this is much more dangerous, since the sizes and layout of these classes at runtime can be different. If I’m still right, let's say that the sizes of the object of the two classes are the same, in this case I could assume that the state of the distributor fits, say, to some area that would otherwise be supplemented, in which case the first approach may work .

How much can I jeopardize this approach, practically speaking? Are there any alternatives that do not have overhead at runtime (and, of course, do not require a third-party interface change and / or line rejection using a user allocator)?

0
source share
1 answer

Not. Using a custom allocator, you are using a different type from std::string . And there is no (legal) way in C ++ to convert this without a copy. Everything that you think can work is not guaranteed by the C ++ standard.

So you have to admit that you need a copy.

+3
source

All Articles