好的,所有人都知道应该像瘟疫一样避免原始指针,并且更喜欢智能指针,但是在实现容器时这个建议是否适用?这就是我试图完成:使用智能指针实现容器
template<typename T> class AVLTreeNode {
public:
T data;
unique_ptr<AVLTreeNode<T>> left, right;
int height;
}
的unique_ptr可以使容器的功能比较麻烦写,因为我不能有暂时指向同一个对象的方式,是优雅的多个原始指针。例如:
unique_ptr<AVLTreeNode<T>> rotate_right(unique_ptr<AVLTreeNode<T>> n1)
{
unique_ptr<AVLTreeNode<T>> n2 = n1->left;
n1->left = n2->right;
n2->right = n1;
// n1 must now be referenced through the longer name n2->right from now on
n2->right->recalculate_height();
n2->recalculate_height();
return n2;
}
(在这个例子中这不是一个大问题,但我可以想象它会如何成为一个问题)。我是否应该将这些问题看作是强烈暗示容器应该使用旧的new
,delete
和原始指针来实现的问题?避免编写析构函数似乎非常麻烦。
除了用传统的包含警卫替换一次编译指示,我已经复制了你的代码,并且不使用clang/libC++复制你的错误。我建议预处理driver.cpp,检查一下,看看你是否看到'unique_ptr'。您看到的行为可能与'unique_ptr'无关,例如不包括''的C++ 11版本。 –
2011-03-29 15:43:41