How can I create shared_ptr for a member?

I'm not sure that I suffer more from documentation errors or a headache, so ...

What I want to do is create a shared_ptr that shares ownership with another, but which refers to an element of the object, not the entire object. Simple example, starting point ...

struct s { int a, b; }; shared_ptr<s> s1 (new s); // pointing to whole object 

From en.cppreference.com constructor (8) shared_ptr ...

 template< class Y > shared_ptr( const shared_ptr<Y>& r, T *ptr ); 

The description mentions "Creates shared_ptr, which shares owner information with r, but contains an unrelated and unmanaged pointer ptr ... for example, in typical use cases, where ptr is a member of an object controlled by r".

So ... Was T just accidentally skipped from the template in this constructor, or am I missing something? In fact, Y looks just as wrong for me, since usually this constructor is correctly described?

What I hope I can do is something like this ...

 shared_ptr<int> s2 (s1, &(s1.get ()->a)); 

s2 points to member a (an int ), but transfers ownership of the entire object using s1 .

Is this reasonable?

+6
source share
3 answers

The parameter T is the template parameter of shared_ptr itself, while the parameter Y is the template parameter for this particular shared_ptr constructor. Something like that:

 template< class T > class shared_ptr { template< class Y > shared_ptr( const shared_ptr<Y>& r, T *ptr ); } 

As for the sample code you posted, this looks good to me.

+9
source

The documentation is correct. You forget that this is the constructor documentation in the class template shared_ptr<T> , that is, the declaration of the constructor class:

 template<typename T> template<typename Y> shared_ptr<T>::shared_ptr(const shared_ptr<Y>& r, T *ptr); 

So in your example T is int and Y is s .

+4
source

T is a class template parameter, not a constructor. And this is exactly as it should be: the pointer to the member must be of the type of the member and forget / delete (see Type-delete) the type of the containing object ( Y , in this case).

The code you posted should work, you can even write it a little easier:

 shared_ptr<int> s2 (s1, &s1->a); 
+2
source

All Articles