I have problem with shared_ptr and 'this' pointer. I found sollution to use enable_shared_from_this but:
std::shared_ptr<Binary_search_tree> x = shared_from_this();
throws exception. How to use it properly in my case?
here is code with context:
#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;
}
}
EDIT: I added whole insert
method code
@Tyker I don't try to access members that way, I need to go throught my tree to add new element using x
and y
pointer. If there is no 'next element' the pointer stays as is and then new element is added.
@G.M. do you mean sth like this:
std::shared_ptr<Binary_search_tree<T>> x(new Binary_search_tree<T>);
x = shared_from_this();