防止结构复制 - 使用递归函数
下面描述了我正在做的事情的一个非常简单(而且愚蠢)的抽象:
class A{
private:
template <typename InIt>
A foo(InIt begin, InIt end, A& a) {
// {begin, ind} is a datastructure containing all "terms" to search for.
auto iter(sub.begin());
auto e(sub.end());
// search trough all elements in original structure.
do
if (FUNC) {
if (++begin != end) {
return iter->foo(begin, end, a.append_values(iter));
//append_values appends a copy of the element's values at iter
//does not copy the sub "trees" of the element at "iter"
//it returns a reference to the appended sub "tree"
} else {
return a;
}
}
} while (++iter != e);
return a;
}
};
Sub 是一个包含类“A”对象的向量 - 因此有效地创建了一个树数据结构。 FUNC 是一个函数,该函数必须为 true 才能将分支“添加”到新树中。
我想知道的是:如果深度(初始开始和结束之间的差异)是“X”,则会“创建”多少个副本。 - 我担心每个深度都会创建一个新的“a”副本。这是我希望阻止的事情。那么我应该通过引用返回吗? - 还是通过指针?
a very simplistic (and silly) abstraction of what I'm doing is described below:
class A{
private:
template <typename InIt>
A foo(InIt begin, InIt end, A& a) {
// {begin, ind} is a datastructure containing all "terms" to search for.
auto iter(sub.begin());
auto e(sub.end());
// search trough all elements in original structure.
do
if (FUNC) {
if (++begin != end) {
return iter->foo(begin, end, a.append_values(iter));
//append_values appends a copy of the element's values at iter
//does not copy the sub "trees" of the element at "iter"
//it returns a reference to the appended sub "tree"
} else {
return a;
}
}
} while (++iter != e);
return a;
}
};
Sub is a vector containing objects of class "A" - so effectivelly creating a tree-datastructure. FUNC is a function that must be true for the branch to be "added" to the new tree.
What I'm wondering is: how many copys are "created" if, say, the depth (difference between initial begin, end) is "X". - I'm fearing that for each depth a new copy of "a" is created. This is something I wish to prevent. So should I return by reference? - Or by pointer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
UncleBens 确实给出了我需要找到“解决方案”的正确问题。
我完全“忘记”你显然也可以使用按引用参数作为输出。当我编辑原始“a”而不是副本时,我不必返回任何内容。
UncleBens indeed gave the correct question I needed to find a "solution".
I completely "forgot" you can obviously use arguments-by-reference as output too. I don't have to return anything as I edit the original "a", not a copy.