我有一个非常简单的POD结构,其中包含如下所示的数组成员。我在使用引用固定长度数组参数memberArray
初始化固定长度数组成员const uint32_t(&rArrayArg)[22]
时遇到问题。我无法访问最终目标环境中的标准库。
成员初始值设定项memberArray{*rArrayArg}
仅复制rArrayArg
arg中的第一个条目。为了查看完整的数组,我需要在构造函数的主体中使用memcpy或(如此处所示)std :: copy。
我有另一个POD结构,它采用2维固定长度数组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,
答案 0 :(得分:3)
我希望我能正确理解问题,然后这应该有效:
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;
}
};
答案 1 :(得分:2)
如果您被允许使用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::array
的内置复制构造函数将完成所有需要完成的工作。