If I pass the unique_ptr back from a function, will the dynamic allocation portion in memory be released and the receive unique_ptr re-allocate a new dynamic portion to hold the value?
Or, whether it's just pass back the addr to the receive unique_ptr, and then it points to null ptr, and then it expire(delete the nullptr)?
First, std::unique_ptr is not copyable. However, it is movable - what this means for your first example is that the 'ok' object is being moved, so it is never being deallocated, rather the data is being transferred to the returned object. I suggest you do some research on move semantics.
So I figured out that it's like the control of the certain dynamic allocation memory block be moved from the "ok" object to the receive object, which means the memory block itself hasn't be changed. Is that right?
#include <iostream>
#include <memory>
struct A
{
A() { std::cout << "A constructed at " << this << '\n' ; }
A( const A& that ) { std::cout << "A copy constructed from " << &that << " to " << this << '\n' ; }
~A() { std::cout << "A at " << this << " destroyed\n" ; }
};
std::unique_ptr<A> foo() {
std::unique_ptr<A> ok(new A);
return ok;
}
int main()
{
{ auto p = foo() ; }
std::cout << "-------------------\n" ;
{
std::unique_ptr<A> fine(new A);
fine = std::unique_ptr<A>(new A);
}
std::cout << "-------------------\n" ;
}
clang++ -std=c++11 -O2 -Wall -Wextra -pedantic-errors main.cpp -lsupc++ && ./a.out
A constructed at 0x11de010
A at 0x11de010 destroyed
-------------------
A constructed at 0x11de010
A constructed at 0x11de030
A at 0x11de010 destroyed
A at 0x11de030 destroyed
-------------------