#include <memory>
#include <vector>
using namespace std;
vector<unique_ptr<int>> e;
void f(unique_ptr<int> u) {
e.emplace_back(move(u));
}
For both Clang and GCC, the above code snippet generates something like:
f(std::unique_ptr<int, std::default_delete<int> >):
mov rsi, QWORD PTR e[rip+8] # rsi: vector.end_ptr
cmp rsi, QWORD PTR e[rip+16] # [e + rip + 16]: vector.storage_end_ptr
je .L52 # Slow path, need to reallocate
mov rax, QWORD PTR [rdi] # rax: unique_ptr<int> u
add rsi, 8 # end_ptr += 8
mov QWORD PTR [rdi], 0 # <==== Do we need to set the argument u to null here?
mov QWORD PTR [rsi-8], rax # *(end_ptr - 8) = u
mov QWORD PTR e[rip+8], rsi # update end_ptr
ret
.L52: # omitted
I was wondering why does the compiler generate mov QWORD PTR[rdi], 0 in this function? Is there any convention that requires compiler to do so?
Moreover, for simpler case like this:
void f(unique_ptr<int> u);
void h(int x) {
auto p = make_unique<int>(x);
f(move(p));
}
Why does the compiler generate:
call operator delete(void*, unsigned long)
at the end of h(), given that p is always nullptr after the invocation of f?