理解shared_ptr时出现问题
我有一个:
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
};
我无法理解为什么这有效:
auto zz = get_parent(get_parent(z));
rb_left_rotate(t,zz);
但这不起作用:
rb_left_rotate(t,get_parent(get_parent(z)));
通过工作我的意思是在 rb_left_rotate 内部我有:
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
......
}
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 cannot 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
......
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
rb_left_rotate()
接受Node_T
作为对非常量的引用。这样的引用只能绑定到左值,即非临时对象。auto zz = get_parent(get_parent(z));
创建这样一个名为zz
的左值。另一方面,在表达式 rb_left_rotate(t,get_parent(get_parent(z))); 中,get_parent(z) 的结果是一个右值,即临时值,不能绑定到对非常量的引用。这与您使用智能指针这一事实无关。
rb_left_rotate()
acceptsNode_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 namedzz
. In expressionrb_left_rotate(t,get_parent(get_parent(z)));
, on the other hand, the result ofget_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.
Node
和Node_T
之间是什么关系?为什么将
get_parent
声明为无参数成员函数,却通过传递参数来调用它?唯一可能修改
x
的是这一行:set_right
做什么?一般来说,如果将
shared_ptr
作为真值传递,而不是对shared_ptr
的引用,您可能会获得更可预测的行为。What is the relationship between
Node
andNode_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:What does
set_right
do?In general, you will probably get more predictable behaviour if you pass around
shared_ptr
s as true values, rather than references toshared_ptr
.