c++ - 创建在 C++ 结构体中声明的数组 a[1] 的多个实例

标签 c++ data-structures

假设我有如下两个结构:

struct address{
  int x;
  int y;
} addr;

struct details{
  int count;
  int size;
  addr addre[1];// Instances of count number of addresses
} detail;                 

如何创建一个变量(例如 det),该变量具有由计数定义的多个 addre 实例?

最佳答案

这是通过在对象末尾(具有固定大小)分配动态大小的容器来减少内存分配数量并提高引用局部性的常见技巧。

但在 C++ 中,使用额外的 member[1] 会导致一些麻烦 - 该成员会自动初始化,而其余元素则不会。最好完全避免声明该成员,而是为元素提供访问器/迭代器。然后手动初始化和销毁​​所有成员。例如:

struct address {
    int x;
    int y;
};

struct details {
    int count;
    int size;

    address* addr_begin() { return reinterpret_cast<address*>(this + 1); }
    address* addr_end() { return addr_begin() + count; }

    static void* operator new(size_t sizeof_details, int count) {
        return ::operator new(sizeof_details + count * sizeof(address));
    }

    static void operator delete(void* p) {
        ::operator delete(p);
    }

    static std::unique_ptr<details> create(int count, int size) {
        return std::unique_ptr<details>(new(count) details(count, size));
    }

    ~details() {
        std::for_each(addr_begin(), addr_end(), [](address& a) { a.~address(); });
    }

private:
    details(int count, int size)
        : count(count)
        , size(size)
    {
        std::uninitialized_fill(addr_begin(), addr_end(), address{});
    }
};

int main() {
    auto det = details::create(10, 10);
}

如果您无法更改结构,则:

#include <new>
#include <algorithm>

struct address {
    int x;
    int y;
};

struct details {
    int count;
    int size;
    address addre[1];
};

details* create_details(int count, int size) {
    void* mem = ::operator new(sizeof(details) + (count - 1) * sizeof(address));
    auto* p = new (mem) details{count, size};
    std::uninitialized_fill(p->addre + 1, p->addre + count, address{});
    return p;
}

void destroy_details(details* p) {
    std::for_each(p->addre + 1, p->addre + p->count, [](address& a) { a.~address(); });
    p->~details();
    ::operator delete(p);
}

int main() {
    auto* p = create_details(10, 10);
    destroy_details(p);
}

关于c++ - 创建在 C++ 结构体中声明的数组 a[1] 的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50250140/

相关文章:

c++ - 没有匹配函数调用 ‘X::X()’

C++11 auto、std::function 和对重载函数的模糊调用

c++ - C++ multimap 容器是如何实现的?

java - 基于第一次排序,再次排序 Sqlite vs Java (Android)

c++ - 在 ',' 错误之前预期为 '...' 或 'struct'

c++ - Protocol Buffer 在解析时是否重用字符串指针?

data-structures - 不存在于 IO monad 中的 Haskell 哈希实现

c - C 中的词频统计(非 C++)

java - 产品和运输信息的数据结构/设计

多单位转换的C#数据结构