lundi 14 août 2017

Unable to move temporary object into the *this object

While trying to create a Binary Search Tree (BST) using C++11 I hit a snag. I can't extract a properly created BST out of the function where it is created. The function reads data from a file (in this case just a number on each line) and builds a BST from those. The building part in the loop works correctly. The problem is I can't get the temporary object moved where I want it to be.

More context: BST<T> is a class that derives publicly from std::unique_ptr<BSTknoop<T>>
BST<T> also inherits the constructors of unique_ptr<BSTknoop<T>> with template<class T> using BSTknoopptr=std::unique_ptr<BSTknoop<T>>; // alias template and using BSTknoopptr<T>::BSTknoopptr; // in the body of the BST<T> class declaration

A BSTknoop<T> is a datastructure with 3 fields one T object to hold the node data two BST&ltT&gt objects left and right (each child is a tree in its own right)

the goal is to move my newly created BST into the calling object. The idea is that in main you can call BST<int> tree; tree.lees(ifs); (with ifs an open input filestream) and tree holds the properly filled BST afterwards.

The function:

template<class T>
istream& BST<T>::lees(istream& is){
    string lijn;
    T knoopwaarde;
    getline(is,lijn);
    knoopwaarde = stoi(lijn);
    BST<T> temptree(new BSTknoop<T>());
    temptree->sl = knoopwaarde;

    for(int i=1; i<DATA_SET_LENGTH ; i++){
        getline(is,lijn);
        knoopwaarde=stoi(lijn);
        temptree.add(knoopwaarde);
        cout<<temptree;
    }
    this->swap(temptree);   /* This does not work */ 
    /* this = move(tmptree);   this does not work either*/
    return is;
}

I have also tried to return a BST<T> from the function and moving that result in the main. That didn't work either.

The program crashes at runtime with an uknown signal.

Side note: I'm unsure as to why BST<T> temptree(new BSTknoop<T>()); works in regard to the templating. The construction works because BST<T> inherits the constructors for unique_ptr<BSTknoop<T>>

Aucun commentaire:

Enregistrer un commentaire