c++ - std::array 与用于连续内存的 C 样式数组

标签 c++ c++11 stl

这是一个仅供兴趣的实验......

我正在尝试制作一个容器,该容器在一个连续的内存块中包含固定数量的字节(例如 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?

来自 the documentation

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/

相关文章:

c++ - 为什么 int 不能用作返回类型的左值,而用户定义的类可以?

c++ - 为什么 TBB 不能将 `int` 转换为 `const tbb::atomic<unsigned int>&` ,但 std::atomic 可以?

c++ - 理解为什么编译时 bool 代数不起作用

c++ - 无需创建 T 元素的 lower_bound 功能

c++ - 从 set<A*,Comparator> 获取 A 成员到 list<A>

c++ - 无法调用其他类 C++ 的析构函数

c++ - 程序在 Visual Studio 2012 中运行,但不在 ideone.com 中运行

C++11 : Why array with shared_ptr can not be deleted by default

c++ - 比较 C++11 中的数组地址

c++ - 在 std::map 中使用 std::auto_ptr 安全吗?