ardabro
ardabro

Reputation: 2061

Why unique_ptr doesn't destroy object immediately when goes out-of-scope?

I have the following piece of code:

struct C
{
    C()             {std::cout << ">>> constructor\n"; }
    ~C()            {std::cout << ">>> destructor\n"; }
};

void bar(std::unique_ptr<C>&& p)
{
    std::cout << "bar\n";
}

int main()
{
    auto instance = std::make_unique<C>();
    std::cout << "after construction\n";
    bar(std::move(instance));                // #1
    std::cout << "after bar\n";
    return 0;
}

On line #1, I'm moving the pointer to the function bar. I was thinking that in this call the pointer-to-C is moved-out from unique_ptr instance and passed to the argument unique_ptr p. If so, then the C destructor should be called at the end of bar()'s execution when argument p is destructed. But it turned out that the instance of C is alive until the end of main()' s execution. The output looks as follows:

>>> constructor
after construction
bar
after bar
>>> destructor

Why does it happen? How to interpret this behavior?

Upvotes: 1

Views: 100

Answers (1)

PeterT
PeterT

Reputation: 8284

std::move doesn't actually move. It just casts it into a an rvalue reference.

Change

void bar(std::unique_ptr<C>&& p)

to

void bar(std::unique_ptr<C> p)

To actually do the move in the move constructor.

Upvotes: 5

Related Questions