Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
944 views
in Technique[技术] by (71.8m points)

c++ - Are pointers to allocated memory outside object's lifetime "invalid pointer[s]" or "pointer[s] to an object"?

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

  • 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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...