Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique_ptr: what is the effect of calling reset before assignment

In c++14, what is the difference between assigning to an existing unique_ptr:

    std::unique_ptr<double> p = std::make_unique<double>(1.0);
    p = std::make_unique<double>(2.0);

and first calling reset before assigning to it:?

    std::unique_ptr<double> p = std::make_unique<double>(1.0);
    p.reset();
    p = std::make_unique<double>(2.0);

I thought adding .reset() before assignment will have not a big impact on the code, but the one without reset() seems to produce different (and more) assembly code when compiled with -O3. Check the code online here:

https://godbolt.org/z/mBApWH

https://godbolt.org/z/JfStmC

like image 232
Liam Keegan Avatar asked Oct 21 '25 05:10

Liam Keegan


1 Answers

I believe most of the differences between compiler output are due to the fact that for one of the two snippets it was able to optimize more stuff out. After all, you just add a couple of constants to a variable. If we're to make optimizer's job a bit more difficult, outputs are nearly identical. There compiler has no idea how foo works and has to produce both calls to it and add results to x, no room to be clever.

To answer you question, the difference is small. Move-assignment operator of unique_ptr frees memory anyway, so calling reset before it is redundant. But, as evident from my link, compiler may omit that operation if it knows that the pointer was reset.

However, calling reset before may be useful if memory held by the pointer will be freed before allocation of new memory, thus reducing memory footprint of the program.

like image 71
Kirill Dmitrenko Avatar answered Oct 23 '25 19:10

Kirill Dmitrenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!