Is this behaviour guaranteed all the time ? The code below creates a char* pointer using temporary unique_ptr. I thought the unique_ptr should get destructed at the end of the statement. To my surprise, the char* still points to valid memory.
void Fill(char* str, long len)
{
for(int i = 0; i < len; ++i)
str[i] = 'a';
}
char* x = std::unique_ptr<char[]>(new char[100]).get();
Fill(x, 100);
std::cout << x << std::endl;
That is invoking undefined behavior. Undefined behavior means anything can happen, including having it appear to work. The temporary
unique_ptris in fact being destructed, and as a result deallocates the 100-elementchararray. You’re reading and writing into a memory location that is not allocated to you anymore.It just so happens that the memory pointed by
xhasn’t been allocated or read/written for something else by the time you’re working with it. But that memory has been already deallocated by the temporaryunique_ptr, so you’re not supposed to mess with it.Just do not do this. If you want to keep the array but not the
unique_ptr, userelease()instead.