Reference std::basic_string specialization of string with custom allocator as a constant object of std::string without overhead?

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

What I am thinking is if we assume a stateless allocator, then, theoretically, two types should be exactly the same in runtime. Therefore, one could simply re-interpret cast the type, 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 an allocator that has a state (which we can have since C++11), I would assume this is a lot more dangerous since sizes and layout of those classes in runtime could be different. If I am right thus far, let's say that sizes of the object of two classes are the same, in that case I could assume that allocator state fits, say, into some area that would have otherwise been padded, in which case the first approach can work.

How much do I put myself in danger with this approach, practically speaking? Are there any alternatives that do not carry any runtime overhead (and of course do not require changing third-party interface and/or giving up a string with custom allocator)?


You don't. By using a custom allocator, you're using a different type from std::string. And there's no (legitimate) way in C++ to convert this without a copy. Anything you think might work will not be guaranteed by the C++ standard.

So you have to accept that you need a copy.

Need Your Help

design pattern run time structure VS compile time Structure

design-patterns design compile-time

I am reading the famous design pattern book by (Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides).

My array isn't recognized as array when it contains only one value

php arrays

In my code, I fill an array using this line in a loop :

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.