Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving a shared_ptr to the method called on the object the shared_ptr points to

Given

struct X {
    void f(std::shared_ptr<X>);
};
auto x(std::make_shared<X>());

I can probably safely do

x->f(std::move(x));

in C++17 because x->f evaluated before the argument to X::f is constructed, right? As far as I know there is no such guarantee in earlier versions of C++. How can I achieve something similar in C++11 and C++14?

PS: Note the same also applies even when using std::unique_ptr instead of std::shared_ptr.

like image 732
jotik Avatar asked Feb 09 '17 10:02

jotik


People also ask

What happens when you move a shared_ptr?

By moving the shared_ptr instead of copying it, we "steal" the atomic reference count and we nullify the other shared_ptr . "stealing" the reference count is not atomic, and it is hundred times faster than copying the shared_ptr (and causing atomic reference increment or decrement).

What is shared_ptr used for?

The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.

What happens when shared_ptr goes out of scope?

when all shared_ptr's pointing to resource goes out of scope the resource is destroyed. A weak_ptr is created as a copy of shared_ptr. It provides access to an object that is owned by one or more shared_ptr instances but does not participate in reference counting.

How can a Weak_ptr be turned into a shared_ptr?

The weak_ptr class template stores a "weak reference" to an object that's already managed by a shared_ptr. To access the object, a weak_ptr can be converted to a shared_ptr using the shared_ptr constructor or the member function lock.


1 Answers

I think the best one can do in C++11 and C++14 without changing the interfaces or using any obscure macros is

auto & refX = *x;
refX.f(std::move(x));
like image 68
jotik Avatar answered Oct 31 '22 14:10

jotik