What's the duration of "pointer not aliased by any other pointer" implication?
Currently Visual C++ is shipped with run开发者_如何转开发time where malloc()
is decorated with __declspec( restrict )
.
MSDN says this decoration states to the compiler that a pointer returned by malloc()
cannot be aliased by any other pointer. Okay, two subsequent calls to malloc()
indeed return distinct pointers. But what happens if I call
void* memory1 = malloc( 10 );
free( memory1 );
void* memory2 = malloc( 10 );
//here memory1 may be equal to memory2
In this case the two pointers can point to the very same location. How does this correlate with cannot be aliased by any other pointer implication of __declspec( restrict )
?
Because once you free(memory1), accessing anything via the memory1 pointer is undefined behavior (nasal demons, and so forth), and hence the compiler can optimize assuming that memory2 is not aliased by any other pointer after the malloc() call.
As for why this matters, assuming the compiler itself has no internal information about the semantics of malloc(), i.e. that it treats it just like any other function, then it cannot assume that the pointer returned is not aliased by any other pointer. The __declspec(restrict)
(or equivalently, __attribute__((malloc))
in GCC) tells the compiler that the pointer is not aliased by any other pointer, which allows some optimizations not possible otherwise.
The standard has this to say about "object lifetime" (§3.8 in N3290):
The lifetime of an object of type T ends when:
— if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
— the storage which the object occupies is reused or released.
After you've free
'd the block pointed to by memory1
, that object is dead. It has ceased to exist. Dereferencing that pointer would be undefined behavior.
memory2
could be assigned the same memory address, but it wouldn't "alias" anything: what was at that location has passed away.
精彩评论