这是一个仅供兴趣的实验......
我正在尝试制作一个容器,该容器在一个连续的内存块中包含固定数量的字节(例如 header )和动态数据 block (例如正文)。在传统的 C 编程中,我会将 char[0]
作为最后一个实例变量,并且我会过度分配 sizeof(struct) + data_length
。
这在 C++ 中有效,但我想要更好的东西。所以我的问题是 std::array
是以指针开头还是可以像原生 C 风格数组一样使用?
这是一些示例代码...
struct pkg_base
{
virtual std::size_t get_body_size() = 0;
virtual void *get_body_ptr() = 0;
};
template<typename _T, std::size_t _N>
struct pkg
: public pkg_base
{
std::uint16_t a;
std::uint16_t b;
std::uint16_t c;
std::array<_T, _N> body{};
std::size_t get_body_size() override
{
return ( body.size() );
}
virtual void *get_body_ptr() override
{
return ( body.data() );
}
};
void _test_package()
{
auto vec = std::vector<std::unique_ptr<pkg_base>>{};
vec.push_back(std::make_unique<pkg<char, 1024>>());
vec.push_back(std::make_unique<pkg<float, 1024>>());
vec.push_back( std::make_unique<pkg<std::string, 1024>>() );
auto const size = vec.front()->get_body_size();
auto const *ptr = static_cast<char *>( vec.front()->get_body_ptr() );
}
最佳答案
So my question is does a std::array start with a pointer or can it be used in the same way as a native C-style array?
This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member.
所以那里没有其他数据成员,只有你想要的 T[N]
数组。
您可以使用 sizeof
或查看代码自行确认这一点。
顺便说一句,以 _[A-Z]
开头的名称保留用于实现,因此您可能不应该调用模板类型参数 _T
和 _N
.
关于c++ - std::array 与用于连续内存的 C 样式数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51325290/