【问题标题】:Statically allocate string array with an initial size静态分配具有初始大小的字符串数组
【发布时间】:2021-10-29 20:32:41
【问题描述】:

我正在开发一个无法使用动态分配的系统。

我想要一个稍后填充的字符串数组。

据我了解,使用

string myArr[20];

不行,我什么时候打电话

myArr[5] = newString

复制构造函数将动态分配新内存,因为初始长度为零。

有可能吗?

【问题讨论】:

  • 可以使用一些静态字符串实现,比如static_string from Boost
  • 不可能静态分配 a std::string。句号。为此,您必须使用 char 数组。
  • @user253751 IIRC,std::string 内部分配有operator new(通过std::allocator<char>),可以由用户替换。理论上,因此可以拥有一些静态分配的内存池并将其用于std::string,而无需堆动态内存分配。我根本不会推荐它,只是说它应该是可能的。
  • @DanielLangr 仍然是动态分配
  • @user253751 是的,我同意,但我想这可以满足 OP 的要求。

标签: c++ arrays string


【解决方案1】:

首先,动态内存分配来自您使用std::string这一事实,而不是来自类 C 数组。如果您想避免这种情况,请使用 const char* 而不是 std::string

其次,我认为通常不鼓励在 C++ 中使用类 C 数组。如果您使用的是 C++11 或更高版本,您可以使用std::array

【讨论】:

    【解决方案2】:

    是的,但它需要编码或外部库,只是为了给你一个基本的想法:

    #include <iostream>
    #include <array>
    #include <string>
    
    // helper class to just give a basic idea, there are better libaries out there :)
    // statically allocates a string buffer of (N+1) chars
    template<size_t N>
    class static_string
    {
    public:
        static_string() = default;
        ~static_string() = default;
    
        void operator=(const std::string& str)
        {
            str.copy(&m_str[0], std::min(str.length(),N) + 1); // string plus trailing 0
        }
    
        const char* c_str() const noexcept
        {
            return &m_str[0];
        }
    
    private:
        std::array<char, N + 1> m_str{}; // init to zero, zo last char is also always *
    };
    
    
    
    int main()
    {
        std::array<static_string<4>, 5> strings;
        strings[3] = "Hello world!"; // only will assign first 4 characters, will not resize memory
    
        // outputs a truncated string
        std::cout << strings[3].c_str();
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-25
      • 2014-12-14
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      相关资源
      最近更新 更多