开发者

Problem understanding shared_ptr

I have a:

template<class K,class V>
struct Node
{
node_ptr parent_;//node_ptr is a shared_ptr<Node<K,V>>
node_ptr& get_parent()const
{
return parent_;
}
void set_parent(node_ptr& p)
{
parent_ = p;
}
//the get set for left and right are analogical
};

I ca开发者_Go百科nnot understand why this works:

auto zz = get_parent(get_parent(z));
rb_left_rotate(t,zz);

but this does not:

rb_left_rotate(t,get_parent(get_parent(z)));

by works I mean that inside rb_left_rotate I have:

template<class Tree_T, class Node_T>
void rb_left_rotate(Tree_T& t,Node_T& x)
{
    auto y = get_right(x);
    set_right(x,get_left(y));
    if (get_left(y))
    {
        set_parent(get_left(y),x);
    }
    auto tmp = get_parent(x);
    //y's current parrent is x
    set_parent(y,tmp);//by works I mean that this line WILL NOT set x to empty
......
}


rb_left_rotate() accepts Node_T as a reference to non-const. Such a reference can only be bound to an l-value, that is, a non-temporary object. auto zz = get_parent(get_parent(z)); creates such an l-value named zz. In expression rb_left_rotate(t,get_parent(get_parent(z)));, on the other hand, the result of get_parent(z) is an r-value, i.e., a temporary value, which can not be bound to a reference to non-const.

This is not related to the fact that you are using a smart pointer.


What is the relationship between Node and Node_T?

How comes you declare get_parent as a no-parameter member function, but call it by passing a parameter?

The only thing that seems likely to modify x is the line:

set_right(x,get_left(y));

What does set_right do?

In general, you will probably get more predictable behaviour if you pass around shared_ptrs as true values, rather than references to shared_ptr.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜