gpt4 book ai didi

c++ - 如何理解 C++17 标准引用中的 [intro.object]/3?

转载 作者:行者123 更新时间:2023-12-01 14:47:42 24 4
gpt4 key购买 nike

[intro.object]/3 N4659(2017 年 3 月 Kona 后工作草案/C++17 DIS)指出:

If a complete object is created ([expr.new]) in storage associated with another object e of type “array of N unsigned char” or of type “array of N std​::​byte” ([cstddef.syn]), that array provides storage for the created object if:

(3.1) the lifetime of e has begun and not ended, and

(3.2) the storage for the new object fits entirely within e, and

(3.3) there is no smaller array object that satisfies these constraints.

[ Note: If that portion of the array previously provided storage for another object, the lifetime of that object ends because its storage was reused ([basic.life]).  — end note ]

[Example:

template<typename ...T>
struct AlignedUnion {
alignas(T...) unsigned char data[max(sizeof(T)...)];
};
int f() {
AlignedUnion<int, char> au;
int *p = new (au.data) int; // OK, au.data provides storage
char *c = new (au.data) char(); // OK, ends lifetime of *p
char *d = new (au.data + 1) char();
return *c + *d; // OK
}
struct A { unsigned char a[32]; };
struct B { unsigned char b[16]; };
A a;
B *b = new (a.a + 8) B; // a.a provides storage for *b
int *p = new (b->b + 4) int; // b->b provides storage for *p
// a.a does not provide storage for *p (directly),
// but *p is nested within a (see below)

— end example]


  • 这段文字应该如何理解?
  • 这如何解决并与有关数组的基本内容相协调,例如大小(数组)?
  • 除了指针,数组还为哪些其他完整对象提供存储?

  • 我将欣赏能够证明此处所说内容的插图,以便我能够完全理解本文。

    最佳答案

    How does that work out and harmonize with the basic things about arrays e.g. sizeof(array)?



    那段话和 sizeof之间没有干扰和数组的其他属性。

    Besides pointers, what other complete objects do arrays provide storage for?



    看来你误解了这些例子。在示例中,通过放置 new 在数组存储中创建了几个对象。照常 new返回一个指向对象的指针,但存储在数组中的是实际对象。

    很难解释得更好,因为你的观点都是基于误解。无论如何,稍微修改一下示例的最后一部分:
    #include <iostream>

    struct A { unsigned char a[32]; };
    struct B {
    unsigned char b[16];
    void hello_world() {
    std::cout << "hello world";
    }
    };

    int main() {
    A a;
    B *b = new (a.a + 8) B; // a.a provides storage for *b

    std::cout << sizeof(a.a) << "\n";
    std::cout << sizeof(b->b) << "\n";

    B& bref = *b;
    bref.hello_world();
    }

    这里有一个 BA 的存储中创建(更具体地说,在 aA 成员中)。将对象放入数组存储中对数组大小没有影响。放置在数组存储中的是一个对象。 new (和位置 new )返回指向该对象的指针,可以取消引用该指针以获取对实际对象的引用。

    关于c++ - 如何理解 C++17 标准引用中的 [intro.object]/3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62232180/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com