Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

(*) As far as I know the Standard allows an implementation to modify the operand of the delete operator, however most implementations do not do that.

int* ptr = new int(0);
delete ptr; //delete is allowed to modify ptr, for example set it to 0
std::cout << ptr; // UB?

Acknowledging (*), is the reading of ptr (in the form of printing it) well-defined?

If delete does modify ptr, is it allowed to set a trap value, which would make reading ptr UB?

See Question&Answers more detail:os

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

1 Answer

In C++14 this is implementation-defined behaviour, [basic.stc.dynamic.deallocation]/4:

If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value, the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage.

Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior.

There is a footnote:

Some implementations might define that copying an invalid pointer value causes a system-generated runtime fault.

This changed since C++11 where the bolded text said "undefined behaviour" and there was no footnote.


So to answer your question, delete ptr; is allowed to set a trap value that would cause a runtime fault for std::cout << ptr. The compiler documentation must specify the behaviour. This is a narrower restriction than UB in which case any unstable behaviour would be permissible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...