【问题标题】:Is the memory of boost::container::string contiguous?boost::container::string 的内存是连续的吗?
【发布时间】:2014-05-30 15:23:58
【问题描述】:

在c++98中,std::string(c++11 required it is contiguous)的内存可能不是连续存储,那么boost::container::string呢?是不是承诺内存是连续的?

如果它是连续的,它可以更自然地与旧版 api 一起使用。

boost::container::string str("some data\0");    
old_api(&str[0]);

不需要再复制到vector中

boost::container::string str("some data\0");
std::vector<char> buffer(str.begin(), str.end());

old_api(&str[0]);

谢谢

【问题讨论】:

  • 为什么不使用c_str()
  • 因为遗留的 api 要求 "char*",虽然 const 正确的类型应该是 char const*(可能是因为早期的 c 编译器不支持 const)

标签: c++ boost


【解决方案1】:

是的,boost::containter::string 内存是连续的。

除非您使用一些具有非普通 referenceconst_refeferencepointer 类型的时髦分配器,否则任何 boost::container::basic_string 特化都有连续内存。

查看字符串的data() 方法:它保证(无条件)恒定时间,并且data()+i == &amp;operator[](i) 用于[i] 中的每个i

【讨论】:

    猜你喜欢
    • 2011-12-10
    • 2011-07-02
    • 2015-01-18
    • 2012-07-09
    • 1970-01-01
    • 2015-09-03
    • 2010-12-15
    • 2011-06-18
    • 2014-09-26
    相关资源
    最近更新 更多