gpt4 book ai didi

c++ - 指向对象生命周期之外分配的内存的指针是 "invalid pointer[s]"还是 "pointer[s] to an object"?

转载 作者:行者123 更新时间:2023-12-03 01:02:33 25 4
gpt4 key购买 nike

C++17(草案 N4659)[basic.compound]/3说:

Every value of pointer type is one of the following:

  • a pointer to an object or function (the pointer is said to point to the object or function), or

  • a pointer past the end of an object ([expr.add]), or

  • the null pointer value ([conv.ptr]) for that type, or

  • an invalid pointer value.

指向对象生命周期之外已分配内存的指针属于这些类别中的哪一个,特别是 //(1)//处的 a 值以下程序中的 (3)b 位于 //(4) 处?

#include<new>
#include<algorithm>

struct S {
~S() { /* Non-trivial destructor */ }
};

struct T {
~T() { /* Non-trivial destructor */ }
};

int main() {
void* a = operator new(std::max(sizeof(S), sizeof(T)));
// (1)
a = new(a) S;
static_cast<S*>(a)->~S();
// (2)
a = new(a) T;
static_cast<T*>(a)->~T();
// (3)
operator delete(a);

void* b = operator new(42);
// (4)
operator delete(b);
}
<小时/>

根据我的理解,指针值在释放时变得无效,而不是在对象的生命周期结束时,但如果指针值是“指向对象的指针”,则>他们指向哪个物体?

最佳答案

To which of these categories belong pointers to allocated memory outside the lifetime of objects, specifically the values of a at // (1) through // (3) and b at // (4) in the following program?

从分配函数返回的指针值(a at //(1)b at //(4)) 目前尚未指定,几乎不可能根据 [basic.compound]/3 中的分类法对它们进行分类,请参阅 https://groups.google.com/a/isocpp.org/d/msg/std-discussion/4NQawIytVzM/eMKo2AJ9BwAJ

In my understanding a pointer value becomes invalid when deallocated, not when the life time of an object ends, but if the pointer values are "pointer[s] to an object", to which object do they point?

当对象还活着时,指向它们所指向的对象。

关于c++ - 指向对象生命周期之外分配的内存的指针是 "invalid pointer[s]"还是 "pointer[s] to an object"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58574379/

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