【问题标题】:std::string::max_size() as static memberstd::string::max_size() 作为静态成员
【发布时间】:2012-11-28 10:38:57
【问题描述】:

为什么max_size 不是std::string 的静态成员?

这可以编译,但我认为所有字符串共有的属性只能通过字符串的实例访问,这很奇怪:

std::size_t max_size = std::string().max_size();

为什么要这样实现?

【问题讨论】:

标签: c++ std


【解决方案1】:

为什么 max_size 不是 std::string 的静态成员?

因为 max_size 返回值取决于字符串实例内部使用的分配器实例。

【讨论】:

  • 是否可以有一个 std::vector 字符串,其中向量中每个实例的 max_size 不同?如果是这样,如何编写一种算法来找到向量中的最短字符串?这样的算法将从 std::size_t shortest_size = std::string().max_size(); 行开始。在迭代向量以更新 shortest_size 的值之前。
  • 可能依赖于分配器,但似乎并非如此。根据std::string documentation:“[...]在没有已知的编译器实现下,字符串(allocator<char>)的内存分配模型受其值的影响[...]”
  • @MickaëlLeBaillif - 据我了解,std::string 是这样(因为它是根据 std::allocator<char> 定义的)。考虑可以定义 LoonyLoopyAllocatortypedef std::basic_string<char,std::char_traits<char>,LoonyLoopyAllocator<char>> LoonyLoopyString;。在这种情况下,max_size() 将不再提供相同的保证。
  • @Baz,如果我理解正确的话,最短的字符串应该使用std::string::size(),而不是max_size()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 2011-06-27
  • 2012-07-28
  • 1970-01-01
相关资源
最近更新 更多