参考std :: basic_string字符串的专业化与自定义分配器作为std :: string的常量对象无开销? [英] Reference std::basic_string specialization of string with custom allocator as a constant object of std::string without overhead?

查看:149
本文介绍了参考std :: basic_string字符串的专业化与自定义分配器作为std :: string的常量对象无开销?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定类 std :: basic_string< char,std :: char_traits< char>,my_allocator< char> > ,如何将它传递给第三方函数,该函数需要一个常量引用 std :: string 任何副本?

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);
}

给定一个具有状态的分配器11),我认为这是一个更危险的,因为这些类在运行时的大小和布局可能不同。如果我到目前为止,让我们说两个类的对象的大小是相同的,在这种情况下,我可以假设分配器状态适合,例如,在一些区域,否则将被填充,在这种情况下,第一种方法可以工作。

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)?

推荐答案

你不会。通过使用自定义分配器,您正在使用 std :: string 中的不同类型。并没有(合法)的方式在C + +转换这个没有副本。

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.

这篇关于参考std :: basic_string字符串的专业化与自定义分配器作为std :: string的常量对象无开销?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆