Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 分割无故障指针向量_C++_Templates_Pointers_Vector - Fatal编程技术网

C++ 分割无故障指针向量

C++ 分割无故障指针向量,c++,templates,pointers,vector,C++,Templates,Pointers,Vector,我在编译下面的代码时遇到了一个分段错误。当我试图释放指针向量时,这来自Destructor实现。你能帮忙吗 我还有一个问题。对我来说,我认为我只能删除向量中的指针,向量将被自动删除。但是,当指针被删除时,向量是否可能不包含任何内容?谢谢 #include <iostream> #include <string> #include <cmath> #include <vector> #include <iterator> using n

我在编译下面的代码时遇到了一个分段错误。当我试图释放指针向量时,这来自Destructor实现。你能帮忙吗

我还有一个问题。对我来说,我认为我只能删除向量中的指针,向量将被自动删除。但是,当指针被删除时,向量是否可能不包含任何内容?谢谢

#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <iterator>

using namespace std;

/* ******************************************************* Node ********************************************************* */

template<class T>
class Node
{
    private:
        T _value;
        vector<Node<T>*> children;

    public:
        Node(T value);
        Node(const Node<T>& node);
        void AddChild(Node<T>* node);
        T getValue() const;
        vector<Node<T>*> returnChildren() const;
        ~Node();
};

template <class T>
Node<T>::Node(T value):_value(value)
{
    children.push_back(NULL);
}

template <class T>
Node<T>::Node(const Node& node):_value(node.getValue()), 
                                children(node.returnChildren())
{
}

template <class T>
void Node<T>::AddChild(Node* node)
{
    if (children[0]==NULL){children.pop_back();};
    children.push_back(node);
}

template <class T>
T Node<T>::getValue() const
{
    return _value;
}

template <class T>
vector<Node<T>*> Node<T>::returnChildren() const
{
    return children;
}

template <class T>
Node<T>::~Node()
{
    for (typename vector<Node<T>*>::iterator it=children.begin() ; it!=children.end() ; it++)
    {
        delete *it;
    }
}



int main()
{
    Node<int> n(3);
    Node<int> nn(4);
    n.AddChild(&nn);
    Node<int>* child= new Node<int>(*(n.returnChildren()[0]));
    cout << (*child).getValue() << endl;
}

基本上有两个错误: 1在~节点中,您应该添加检查以查看指向子节点的指针是否为空,否则删除空指针将导致seg故障
2将主函数节点实例化为函数堆栈中的局部变量,而不是堆中的局部变量,将在函数退出时自动启动~节点:这意味着另一个seg错误,因为您试图删除两次相同的指针。

您正在对指向堆栈上对象的指针调用delete。你认为会发生什么?哦,是的,我在堆栈上创建了nn。我刚用新的创建了它,它很有效。谢谢1是不正确的。删除null不会导致seg故障。2是问题的准确标识,但删除两次不是准确的描述。使用局部变量的地址调用delete一次就足以处理seg故障。