将shared_ptr移动到shared_ptr指向的对象上调用的方法

jot*_*tik 6 c++ shared-ptr c++11 c++14 c++17

特定

struct X {
    void f(std::shared_ptr<X>);
};
auto x(std::make_shared<X>());
Run Code Online (Sandbox Code Playgroud)

我可以安全地做

x->f(std::move(x));
Run Code Online (Sandbox Code Playgroud)

在C++ 17中因为x->fX::f构造参数之前进行了评估,对吧?据我所知,在早期版本的C++中没有这样的保证.如何在C++ 11和C++ 14中实现类似的功能?

PS:请注意,即使使用std::unique_ptr而不是也适用std::shared_ptr.

jot*_*tik 4

我认为在不更改接口或使用任何晦涩的宏的情况下,在 C++11 和 C++14 中可以做的最好的事情是

auto & refX = *x;
refX.f(std::move(x));
Run Code Online (Sandbox Code Playgroud)