代码之家  ›  专栏  ›  技术社区  ›  johnco3

初始化固定C数组成员结构

  •  4
  • johnco3  · 技术社区  · 7 年前

    我有一个非常简单的POD结构,其中包含一个数组成员,如下所示。初始化固定长度数组成员时遇到问题 memberArray 使用参考固定长度数组参数 const uint32_t(&rArrayArg)[22] 。我将无法在最终目标环境中访问标准库。

    成员初始值设定项 memberArray{*rArrayArg} 仅复制 rArrayArg 参数。为了查看完整的数组,我需要在构造函数的主体中memcpy或(如图所示)std::copy。

    我有另一个POD结构,它采用二维固定长度数组 const uint32_t(&rArrayArg)[4][5] 它将用于初始化相应的2d成员,因此首选成员初始化语法的通用解决方案。

    struct TestStruct {
        explicit TestStruct(
            const uint32_t(&rArrayArg)[22])
            : memberArray{*rArrayArg}
        {
            //std::copy(std::cbegin(rArrayArg), std::cend(rArrayArg), memberArray);
        }
    
        uint32_t memberArray[22];
    
        // this stream helper is only present for debugging purposes
        // in the actual target environment, I will not have access to std:: 
        friend std::ostream& operator<<(std::ostream& os, const TestStruct& rhs) {
            os << "TestStruct: ";
            for (auto next : rhs.memberArray) {
                os << next << ",";
            }
            return os;
        }
    };
    

    以下内容 live demo 显示传递部分填充的固定数组参数的结果 uint32_t fixedLenArg[22] = {1,2,3,4,5,6}; 到显式构造函数。打印结果显示:

    TestStruct: 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    

    很明显,只复制了第一个参数。如果我在构造函数主体中取消对std::copy的注释(这是调试,因为我在最终环境中没有访问std::copy的权限),我会得到以下结果:

    TestStruct: 1,2,3,4,5,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Yuki    7 年前

    我希望我正确理解了这个问题,然后这应该会起作用:

    struct TestStruct {
      constexpr static size_t arraySize = 22;
    
      explicit TestStruct(const uint32_t(&rArrayArg)[arraySize]) : memberArray() {
        for (size_t i = 0; i < arraySize; ++i)
            memberArray[i] = rArrayArg[i];
      }
    
      uint32_t memberArray[arraySize];
    
      // this stream helper is only present for debugging purposes
      // in the actual target environment, I will not have access to std::
      friend std::ostream& operator<<(std::ostream& os, const TestStruct& rhs) {
        os << "TestStruct: ";
        for (auto next : rhs.memberArray) {
          os << next << ",";
        }
        return os;
      }
    };
    
        2
  •  2
  •   Xirema    7 年前

    如果允许使用 std::array ,这变得非常琐碎:

    struct TestStruct { 
        explicit TestStruct(std::array<uint32_t, 22> const& rArrayArg)
            : memberArray{rArrayArg}
        {}
    
        std::array<uint32_t, 22> memberArray;
    
        // this stream helper is only present for debugging purposes
        // in the actual target environment, I will not have access to std:: 
        friend std::ostream& operator<<(std::ostream& os, const TestStruct& rhs) {
            os << "TestStruct: ";
            for (auto next : rhs.memberArray) {
                os << next << ",";
            }
            return os;
        }
    };
    

    的内置副本构造函数 std::阵列 将完成所有需要进行的工作。