我对shared_ptr和'this'指针有疑问。我发现可以使用enable_shared_from_this的解决方案,但是:
std::shared_ptr<Binary_search_tree> x = shared_from_this();
抛出异常。在我的情况下如何正确使用它?
这是带有上下文的代码:
#pragma once
#include <memory>
#include <string>
bool def_comparator(int x, int y) {
if (x>y)
{
return true;
}
else {
return false;
}
};
template <typename T>
class Binary_search_tree : public std::enable_shared_from_this<Binary_search_tree<T>>
{
public:
std::shared_ptr<Binary_search_tree> up;
std::shared_ptr<Binary_search_tree> left;
std::shared_ptr<Binary_search_tree> right;
int key;
T data;
bool(*comparator)(int, int);
Binary_search_tree(T x, const int key, bool(*comparator)(int, int))
{
if (comparator==NULL)
{
this->comparator = &def_comparator;
}
else {
this->comparator = comparator;
}
this->data = x;
this->key = key;
}
Binary_search_tree()
{
}
~Binary_search_tree()
{
}
bool insert(T data, const int key)
{
std::shared_ptr<Binary_search_tree> y;
std::shared_ptr<Binary_search_tree> x = shared_from_this();
if (comparator(key, x->key))
{
x = x->left;
}
else {
x = x->right;
}
while (x != NULL)
{
y = x;
if (comparator(key,x->key))
{
x = x->left;
}
else {
x = x->right;
}
}
Binary_search_tree<T> *tmp = new Binary_search_tree<T>(data, key, this->comparator);
tmp->up = y;
if (tmp->key == y->key)
{
return false;
}
if (comparator(tmp->key,y->key))
{
y->left = shared_ptr<Binary_search_tree<T>>(tmp);
}
else {
y->right = shared_ptr<Binary_search_tree<T>>(tmp);
}
return true;
}
}
编辑:我添加了整个 insert
方法代码
@Tyker我不尝试以这种方式访问成员,我需要遍历树以使用x
和y
指针添加新元素。如果没有“下一个元素”,指针将保持不变,然后添加新元素。
@GM你的意思是这样吗?
std::shared_ptr<Binary_search_tree<T>> x(new Binary_search_tree<T>);
x = shared_from_this();