problems about smart pointers

it's a bout unique_ptr.

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)?

1
2
3
4
unique_ptr<double> func1(){
    unique_ptr<double> ok(new double(4.9));
    return ok;
}
And another question is:

If code like this:
1
2
unique_ptr<double> fine(new double(5.0));
fine = unique_ptr<double>(new double(4.0));


will the former dynamic allocation be de-allocated?
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?
We can check it out by writing a small test program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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
-------------------

http://coliru.stacked-crooked.com/a/012eb07679da4d3c
JLBorges, thanks. It's really a good way.
Topic archived. No new replies allowed.