CPP核心指南中的布局中的浪费空间

时间:2019-01-31 09:51:54

标签: c++ cpp-core-guidelines

我正在阅读 CPP核心准则P.9: Don’t waste time or space

示例,错误:

struct X {
    char ch;
    int i;
    string s;
    char ch2;

    X& operator=(const X& a);
    X(const X&);
};

X waste(const char* p)
{
    if (!p) throw Nullptr_error{};
    int n = strlen(p);
    auto buf = new char[n];
    if (!buf) throw Allocation_error{};
    for (int i = 0; i < n; ++i) buf[i] = p[i];
    // ... manipulate buffer ...
    X x;
    x.ch = 'a';
    x.s = string(n);    // give x.s space for *p
    for (gsl::index i = 0; i < x.s.size(); ++i) x.s[i] = buf[i];  // copy buf into x.s
    delete[] buf;
    return x;
}

void driver()
{
    X x = waste("Typical argument");
    // ...
}

然后它指出:

  

... 请注意,X的布局可确保至少浪费6个字节(并且很可能更多)。

为什么一定要浪费6个字节?以及如何解决(除非构造函数声明是造成示例浪费的原因)

1 个答案:

答案 0 :(得分:1)

该结构以默认对齐方式开始。第一个成员ch已对齐。 i是一个int,并且必须对齐四个字节(当int为四个字节时),因此在chi之间,您将获得三个字节的填充。在ch2之后的结构末尾也是如此,在那里您将获得三个填充字节。插入这些元素是为了使X x[2];两个元素在内存中正确对齐。

struct X {
    char ch;
    char padding1[3]; // so that int i is int-aligned (four bytes)
    int i;
    string s;
    char ch2;
    char padding2[3]; // end of struct must also be aligned
};
相关问题