是指向对象生命周期之外的已分配内存的指针“无效指针"吗?或“对象的指针"? [英] Are pointers to allocated memory outside object's lifetime "invalid pointer[s]" or "pointer[s] to an object"?
问题描述
C ++ 17(草稿N4659) [basic.compound] /3 说:
C++17 (draft N4659) [basic.compound]/3 says:
指针类型的每个值都是以下之一:
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
指向对象([expr.add])末尾的指针,或者
a pointer past the end of an object ([expr.add]), or
该类型的空指针值([conv.ptr]),或
the null pointer value ([conv.ptr]) for that type, or
无效的指针值.
在以下对象程序的生命周期之外,这些类别中的哪一个属于指向已分配内存的指针,特别是// (1)
到// (3)
的a
和// (4)
的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?
#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);
}
据我了解,指针值在释放时变为无效,而不是在对象的生命周期结束时失效,但如果指针值为"指向对象的指针",则为他们指向哪个对象?
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?
推荐答案
在以下对象程序的生命周期之外,这些类别中的哪一个属于指向已分配内存的指针,特别是在
// (1)
到// (3)
的a
和在// (4)
的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)
andb
at// (4)
in the following program?
当前尚未指定从分配函数(// (1)
的a
和// (4)
的b
)返回的
指针值,几乎无法根据[basic.compound]/3中的分类法对其进行分类. ,请参见 https://groups.google. com/a/isocpp.org/d/msg/std-discussion/4NQawIytVzM/eMKo2AJ9BwAJ
Pointer values returned from allocation functions (a
at // (1)
and b
at // (4)
) are not currently specified and it is barely possible to classify them according to the taxonomy in [basic.compound]/3, see 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?
他们指向对象时该对象还活着.
To the object they pointed to when the object was alive.
这篇关于是指向对象生命周期之外的已分配内存的指针“无效指针"吗?或“对象的指针"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!