Can unused function-arguments become optimized away?


I’m trying to ensure an object – wrapped by a shared_ptr – is alive as long as a function is executed by passing it as value. However inside the function the object is not used at all, so I just want to use it for ‘pinning’:

void doSomething(std::shared_ptr<Foo>) {
    // Perform some operations unrelated to the passed shared_ptr.

int main() {
    auto myFoo{std::make_shared<Foo>()};
    doSomething(std::move(myFoo)); // Is 'myFoo' kept alive until doSomething returns?
    return 0;

I did check the behavior on different optimization-levels (GCC) and it seems that it works as intended, however I don’t know whether the compiler still may optimize it away in certain scenarios.

Source: Windows Questions C++