jeudi 13 juillet 2017

C++ template class causes infinite loop on destruction

So, I have base class and derived class with template It works fine, until I try to delete derived classes. I tested making derived class as one piece, or without template and it worked fine, but when I split it to .h and .cpp files I'm getting errors

This works fine

template<class T>
    class NodeTT: public Node
    {
    private:
        T _data;
    public:
        NodeTT(Node* parent = nullptr):Node(parent){}
        NodeTT(T data, Node* parent = nullptr):Node(parent),_data(data){}
        ~NodeTT(){std::cout<<"deriv destr"<<std::endl;}
        void show(){
            std::cout<<_data<<std::endl;
            for(Node* childNode : _children)childNode->show();
        }
    };

Same class in two files

HEADER
#include <iostream>
#include <node.h>

template<class T>
class TNode: public Node
{
private:
    T _data;
public:
    TNode(Node* parent = nullptr);
    TNode(T data, Node* parent = nullptr);
    ~TNode();
    void show();
};

SOURCE
template<class T>
TNode<T>::TNode(Node *parent) : Node(parent){}

template<class T>
TNode<T>::TNode(T data, Node* parent): Node(parent),_data(data){}

template<class T>
TNode<T>::~TNode(){
    std::cout<<"deriv destr"<<std::endl;
}

template<class T>
void TNode<T>::show(){
    std::cout<<_data<<std::endl;
    for(Node* childNode : _children)childNode->show();
}

template class TNode<int>;
template class TNode<float>;
template class TNode<std::string>;

And this destructor of base class

Node::~Node(){
    std::cout<<"base destr"<<std::endl;
    for(Node* childNode : _children)
    {
       delete childNode;
    }
    delete _parentNode;
    _children.clear();
}

in output i'm getting infinite messages "base destr", so any help with pointing my mistakes will be appreciated

Sorry for my English.

Aucun commentaire:

Enregistrer un commentaire