【发布时间】:2020-12-23 03:21:46
【问题描述】:
我从 C API 获取一个数组,我想将它复制到 std::array 以在我的 C++ 代码中进一步使用。那么这样做的正确方法是什么?
我2个用这个,一个是:
struct Foo f; //struct from C api that has a uint8_t kasme[32] (and other things)
c_api_function(&f);
std::array<uint8_t, 32> a;
memcpy((void*)a.data(), f.kasme, a.size());
还有这个
class MyClass {
std::array<uint8_t, 32> kasme;
int type;
public:
MyClass(int type_, uint8_t *kasme_) : type(type_)
{
memcpy((void*)kasme.data(), kasme_, kasme.size());
}
...
}
...
MyClass k(kAlg1Type, f.kasme);
但这感觉相当笨重。有没有一种惯用的方法,可能不涉及 memcpy ?对于 MyClass`,也许我会更好 构造函数采用 std::array 移动到成员中,但我也无法弄清楚这样做的正确方法。 ?
【问题讨论】:
-
为什么不
std::copy? -
除了尚未正式发布:
auto x = std::to_array<uint8_t, 32>(cArrayPtr);
标签: c++ arrays algorithm initialization copy