[英]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? 给定类std::basic_string<char, std::char_traits<char>,my_allocator<char> >
,如何将它传递给第三方函数,该函数需要对类std::string
的对象进行常量引用std::string
没有制作任何副本?
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. 给定一个具有状态的分配器(我们可以从C ++ 11开始),我认为这更危险,因为运行时这些类的大小和布局可能不同。 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
. 通过使用自定义分配器,您使用的是与 std::string
不同的类型。 And there's no (legitimate) way in C++ to convert this without a copy. 并且在C ++中没有(合法的)方式来转换它而没有副本。 Anything you think might work will not be guaranteed by the C++ standard. C ++标准无法保证您认为可能有效的任何内容。
So you have to accept that you need a copy. 所以你必须接受你需要一份副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.