更新时间:2023-11-09 23:35:16
您只需要使 B
模板:
template <typename T>
class B {
A<T>* a;
public:
B(A<T>* ar) : a(ar) {}
};
这是基于共享指针的问题。作为读者,我尚不清楚 B
是否取决于外部的 A
所有权,或者如果 A< *
的所有权也正在转移到 B< T>
。 C ++ 11为您提供了一些共享指针的出色工具,我强烈建议您利用它们。
This runs upon the problem of shared pointers. It's unclear to me as the reader if B<T>
will depend upon an A<T>*
that is externally owned, or if the ownership of A<T>*
is also being transfered to B<T>
. C++11 has provided you some great tools for sharing pointers, and I'd strongly recommend that you take advantage of them.
如果要共享 A&T; *
,但它将使用 shared_ptr
。
如果您转让 A< T> *
的所有权>在构造上,请使用 unique_ptr
。
If you want to share A<T>*
but it will be owned externally use a shared_ptr
.
If you transferring ownership of A<T>*
on construction, signify that by using a unique_ptr
.
编辑:
B< T>
包含成员对象 A< T>
。但是它是由指针持有的。 通过指针或引用持有成员表示对象的使用是共享的,或者所有权是外部的。
B<T>
contains a member object A<T>
. But it is held by pointer. Holding a member by pointer or reference indicates that the objects use is shared or ownership is external.
在不知道您的设计的情况下,很难展示好的设计原则,因此我在这里给出一些可选的情况,并建议您遵循与您的情况相符的建议:
Without knowing your design it's hard to present a good design principle, so I'll give some optional situations here with the recommendation that you adhere to the one that matches your situation:
B< T>
的 A< T>
成员仅在单个 B< ; T>
对象,该成员需要在 B< T>
的构造函数或Emplace构建的内部创建 B
的 A< code>成员
B< T>
它应该是 B
类的静态成员 A<
将由 B< T>
拥有,但只能由指针使用来接收 unique_ptr< A< T>> c而不是 A< T> *
作为成员类型i>
- 如果
A&T;
将在外部共享并且不会被删除,只要至少保留了对其的一个引用,请使用 shared_ptr< A< T>>
而不是 A&T; *
作为成员类型
- 如果
A< T>
是外部拥有的,并且可能已被销毁或未被销毁,请使用 weak_ptr< A< T>>
而不是 A< T **
作为成员类型
B<T>
's A<T>
member is only used within the single B<T>
object, that member needs to be created within B<T>
's constructor or emplace constructedB<T>
's A<T>
member is shared among all B<T>
it should be a static member of the B
classA<T>
will be owned by B<T>
but may only be received by pointer use a unique_ptr<A<T>>
rather than A<T>*
as the member typeA<T>
will be shared externally and will not be deleted as long as at least one reference to it is maintained use use shared_ptr<A<T>>
rather than A<T>*
as the member typeA<T>
is owned externally and may or may not have been destroyed use weak_ptr<A<T>>
rather than A<T>*
as the member type