I liked std::unique_ptr the moment I saw it back in c++11, but I questioned it's effectiveness for quite a while. (see link below for link to live code) :
#include <memory>
std::unique_ptr<int> get();
extern std::unique_ptr<int> val;
void foo()
{
val = get();
}
This gave me 16 instructions on last clang with -O3. But what is more interesting is that it generated two calls to delete, even though the second one will never be called.
Than I tried to do it like this:
void foo()
{
auto ptr = get().release();
val.reset(ptr);
}
And suddenly it's just 11 instructions. Then I went deeper and hacked unique_ptr move ctor. Originally it is implemented as reset(__u.release());. I basically just reordered it as follows:
auto& ptr = _M_ptr();
if (ptr)
_M_deleter()(ptr);
ptr = __u.release();
Aaand.... 11 instructions as in hand-managed version. It is slightly different but seems ok.
I saved my experiments here.
Can someone point out is that it's I'm missing something or it's actually somehow intended?