规则三为内部类,外部类 [英] Rule of three for inner class, outer class
问题描述
假设我的类定义为
#ifndef A_H
#define A_H
#include <vector>
class A
{
int n;
std::vector<A::B> elements;
public:
A();
A(int);
class B
{
int m;
A* a;
public:
B();
B(int);
B(int, A*);
};
};
#endif
A.cpp / p>
A.cpp
#include "A.h"
A::A()
: n(0)
{
}
A::A(int x)
: n(x), elements(std::vector<A::B>(n))
{
for (int j = 0; j < this->n; j++)
{
B newElement(j, this);
this->elements[j] = newElement;
}
}
A::B::B()
: m(0), a(0)
{
}
A::B::B(int j)
: m(j), a(0)
{
}
A::B::B(int j, A* aPtr)
: m(j), a(aPtr)
{
}
如何定义复制构造函数,重载赋值运算符和析构函数,递归删除,我避免,如果可能,必须使用 new
? A :: B
需要指向 A
的指针来定义程序员可能决定添加的操作符。此外,程序员可以决定编写扩展A的 / p>
How should I define copy constructors, overloaded assignment operators, and destructors such that I avoid infinite recursion on deletion, and that I avoid, if possible, having to use new
? A::B
needs pointer to A
to define operators that programmer may decide to add. Also, programmer may decide to write class C that extends A and C::D
that extends A::B
推荐答案
我应如何定义复制构造函数,重载赋值运算符和析构函数,以避免无限递归如果可能,我避免使用新
How should I define copy constructors, overloaded assignment operators, and destructors such that I avoid infinite recursion on deletion, and that I avoid, if possible, having to use new
A :: elements的所有权
由您的声明决定。 〜A
将销毁owned元素成员中的任何 B
。这意味着 A :: B :: a
可能必须被视为未知的指针,并且在〜B
运行。如果在某些情况下 A :: B :: a
由 B
的实例拥有,则 B
可能需要添加一个成员来跟踪此所有权,并且只在这些情况下释放。或者, A :: B :: a
可以被声明为 std :: shared_ptr< A>
(或类似)。但是,请记住,如果所有权是循环的, std :: shared_ptr
仍然可能会泄露。
Ownership of A::elements
is determined by your declaration. ~A
is going to destroy any B
's in the owned elements member. This means that A::B::a
likely has to be treated as an unowned pointer and not deleted when ~B
is run. If, under some circumstances, A::B::a
is owned by an instance of B
, then B
likely needs to add a member to track this ownership and free a only under these circumstances. Alternatively A::B::a
could be declared as std::shared_ptr<A>
(or similar). However, remember that std::shared_ptr
can still potentially leak if ownership is circular.
这种模糊性和复杂性如果有可能确定什么拥有什么,并得出一个比一切都拥有一切更不透明的关系。
This ambiguity and complexity would be avoided if it's possible to determine 'what owns what' and come up with a relationship that is less opaque than 'everything owns everything else'.
这篇关于规则三为内部类,外部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!