我正在写一个树状容器,其中每个“节点”都有一个带分支/子树的列表,目前我的头像:
class _tree {
public:
typedef _tree* tree_ptr;
typedef std::list<_tree> _subTreeTy;
explicit _tree(const _ValTy& v, const _NameTy& n); //create a new tree
_tree(const _ValTy& v, const _NameTy& n, tree_ptr _root);
//create a new tree and add it as branch to "_root".
~_tree();
void add_branch(const _tree& branch); //add by copy
void add_branch(_tree&& branch); //add by move
private:
_subTreeTy subtrees;
_ValTy value;
_NameTy name;
};
_tree::_tree(const _ValTy& v, const _NameTy& n, tree_ptr _root)
: root(_root),
value(v),
name(n)
{
_root->add_branch(*this); //not rvalue(???)
}
现在第二个构造函数会在_root
中创建一个树 - 但是这如何与调用一起工作(忽略私有违规):
_tree Base(0,"base");
_tree Branch(1, "branch", &Base);
Base.subtrees.begin()->value = 8;
std::cout << Branch.value;
我如何才能使Branch
&amp; *Base.subtrees.begin()
是指同一个节点?或者我应该走另一条路。使用add_branch()
创建分支/子树?
答案 0 :(得分:3)
移动语义是关于移动对象的内部,而不是移动对象(作为类型的内存)本身。最好以值和不变量来考虑它,因为即使考虑到移动,C ++仍然具有值语义。这意味着:
std::unique_ptr<int> first(new int);
// invariant: '*this is either null or pointing to an object'
// current value: first is pointing to some int
assert( first != nullptr );
// move construct from first
std::unique_ptr<int> second(std::move(first));
// first and second are separate objects!
assert( &first != &second );
// New values, invariants still in place
assert( first == nullptr );
assert( second != nullptr );
// this doesn't affect first since it's a separate object
second.reset(new int);
换句话说,虽然您可以通过执行*this
将表达式std::move(*this)
转换为rvalue,但由于std::list<_tree>
使用值语义和_tree
,因此无法实现有价值语义本身。 *Base.subtrees.begin()
是与Branch
不同的对象,因为对前者的修改不会影响后者。
如果你想要(或需要),那么切换到引用语义,例如使用std::shared_ptr<_tree>
和std::enable_shared_from_this
(然后在构造函数中使用_root->add_branch(shared_from_this())
)。我不会推荐它,但这可能会变得混乱。在我看来,价值语义是非常理想的。
使用值语义,使用您的树可能如下所示:
_tree Base(0, "base");
auto& Branch = Base.addBranch(1, "branch");
即,addBranch
返回对新构造节点的引用。在顶部喷洒一些移动语义:
_tree Base(0, "base");
_tree Tree(1, "branch); // construct a node not connected to Base
auto& Branch = Base.addBranch(std::move(Tree));
// The node we used to construct the branch is a separate object
assert( &Tree != &Branch );
严格地说,如果_tree
是可复制的,则移动语义不是必需的,Base.addBranch(Tree);
也可以。