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
.
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).
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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With