简体   繁体   English

如何为成员创建一个shared_ptr?

[英]How can I create a shared_ptr to a member?

I'm not sure if I'm suffering more from a documentation error or a headache, so... 我不确定我是否遭受文档错误或头痛的困扰,所以...

What I want to do is create a shared_ptr that shares ownership with another, but which references a member of the object instead of the whole object. 我想做的是创建一个与另一个共享所有权的shared_ptr,但是它引用对象的成员而不是整个对象。 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) of shared_ptr is... en.cppreference.com来看 ,shared_ptr的构造函数(8)是...

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

The description mentions "Constructs a shared_ptr which shares ownership information with r, but holds an unrelated and unmanaged pointer ptr ... such as in the typical use cases where ptr is a member of the object managed by r". 描述中提到“构造一个与r共享所有权信息,但保存不相关且不受管理的指针ptr ...的shared_ptr,例如在典型的用例中ptr是r管理的对象的成员”。

So... Was T just accidentally missed from the template in that constructor, or am I missing something? 所以... T只是偶然从该构造函数中的模板中丢失了,还是我缺少了什么? In fact, Y looks like it's wrong to me too, so just generally is that constructor described correctly? 实际上,Y看起来也对我来说是错误的,因此,通常来说,构造函数是否正确描述?

What I'm hoping I can do is something like this... 我希望我能做的是这样的事情...

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

s2 points to member a (an int ), but shares ownership of the whole object with s1 . s2指向成员a (一个int ),但与s1共享整个对象的所有权。

Is that sane? 那样理智吗

The T parameter is a template parameter on the shared_ptr itself, whereas the Y parameter is a template parameter on that particular shared_ptr constructor. T参数是shared_ptr本身的模板参数,而Y参数是该特定shared_ptr构造函数的模板参数。 Something like this: 像这样:

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

As for the example code you've posted, that looks fine to me. 至于您发布的示例代码,对我来说很好。

The documentation is correct. 该文档是正确的。 You're forgetting that this is the documentation of a constructor on the class template shared_ptr<T> ie the class-qualified declaration of the constructor is: 您忘记了,这是类模板shared_ptr<T>上的构造函数的文档,即构造函数的类限定声明为:

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 . 因此,在您的示例中TintYs

T is the template parameter of the class, not of the constructor. T是类的模板参数,而不是构造函数的模板参数。 And this is exactly as it needs to be: A pointer to a member has to have the type of the member and forget/erase (see type-erasure) the type of the containing object ( Y , in this case). 这恰好是需要的:指向成员的指针必须具有成员的类型,并且要忘记/擦除(请参阅类型擦除)包含对象的类型(在这种情况下为Y )。

The code you posted should work, you can even write it a little simpler as: 您发布的代码应该可以工作,您甚至可以将其编写为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM