Reputation: 153
I was trying to understand when the memory owned by shared (smart) pointers are cleared on calling execv()
from the code.
Assume the following code:
#include <memory>
class Test { public: ~Test() { std::cout << "Test destroyed."; } };
int main() {
std::shared_ptr<Test> p = std::make_shared<Test>();
std::shared_ptr<Test> q = p;
p.reset();
// Call execv().
execv("/bin/program", "/bin/program");
// This code will never be executed, because execv() replaces the current process image.
// Will the memory pointed to by q be cleared?
return 0;
}
On calling execv("/bin/program", "/bin/program");
the current process image is replaced with the new process image.
My question is will the memory owned by the shared pointer be cleared or not when the new process starts or should we call q.reset()
explicitly before calling execv("/bin/program", "/bin/program");
?
I tried looking at the documentation of execv()
but could not find any mention of smart pointers.
Upvotes: 0
Views: 132
Reputation: 56477
From C++ perspective you are simply making a call. It is not aware that the process is being replaced with another one. And it won't treat that call differently from any other call. You are not leaving scope, so no destructor will run. In particular, shared pointers won't have opportunity to finalize themselves.
The memory will be wiped out (because of how execv works), but not in a graceful way. In particular if you expect some action to run on destruction then you have to finalize stuff manually. This is especially important if you are dealing with resources outside of the process.
Also, you won't find anything about smart pointers in execv docs. It is part of POSIX C bindings, which is a C library. While technically it can be used by C++ (because of its compatibility with C), it is not aware of non-C features of C++. Execv (and POSIX in general) doesn't even know what smart pointers are.
Upvotes: 3
Reputation: 30840
Syscalls like execve
or the computer catching fire are an "out of context" problem for C++. When you call execve
, the program flow transitions to the kernel. The kernel completely reinitializes the memory space and the original program does not get a chance to run again. The smart pointer and the memory it used to manage simply ceases to exist.
If you wanted to use the smart pointer's release action to perform side effects that are visible outside of the program (eg file or network I/O), release them by hand before calling execve
.
Upvotes: 4