According to my textbook, if a unique_ptr points, say 'unikp', to a dynamically allocated array, then after the user use release() member function on 'unikp', the memory of the dynamically allocated array which 'unikp' points to should be automatically freed. In order to test this, I wrote the code as shown below:
on my computer, which should be indicating that the member function release() cannot free the corresponding memory and only reset() can free the memory.
Am I right about this? Can someone help me out here? Really appreciate it!
Memory always exists. It is not created or destroyed. Allocating and freeing memory is simply the act of gaining and giving away permission to use certain parts of memory. What happens after you give away permission is impossible to determine - you shouldn't go back and look at or alter memory you no longer have permission to access.
If a standard library function says it does something, it does that. It's not like some poorly developed product with horrible "documentation". It's the C++ Standard Library - people vote on this stuff in committees.
release() releases control of the pointer without deleting; the intention being that you are giving control of the deletion to whatever you are passing it to, so the unique_ptr no longer owns it.
As it stands, you would have a memory leak with unikp1 if you didn't have another pointer to it like x1.
Also, your intuition about whether or not the pointer was deleted by looking at x1/x2 is invalid, as accessing memory that has been deleted (like you are doing with x2) is invoking undefined behavior and could do anything.
Thanks for your replies. I understand that release() releases control of the pointer from a unique_ptr object without deleting for the case where the unique_ptr is pointing to a non-array type object. I was just confused over this statement given by my textbook saying that if the unique_ptr is pointing to a dynamic array, then calling release() on it would "automatically use delete[] to destroy its pointer". Maybe I interpreted it wrongly or something. Anyway, just to make sure, release() does not free the memory of the dynamic object it's pointing to even if the dynamic object here is actually a dynamic array, is it correct?
Anyway, just to make sure, release() does not free the memory of the dynamic object it's pointing to even if the dynamic object here is actually a dynamic array, is it correct?
It does free the object. It does not fill the content with other values.