【问题标题】:why is my copy constructor producing a segfault everytime i try to alter the object为什么每次我尝试更改对象时我的复制构造函数都会产生段错误
【发布时间】:2013-02-26 13:01:04
【问题描述】:
/* Copy constructor */
List(const List<value_type>& list)
{
    // for (iterator it = list.begin(); it != list.end(); ++it); 
    //   this->push_back(*it);
    // The commented part above is what I want it to do.
    std::cout << "empty = " << this->empty(); // no seg fault;
    std::cout << "size = " << this->size(); // also causes a seg fault
    this->push_back("string") // causes a seg fault
}

尝试运行此代码会使我的程序出现段错误。似乎每次我尝试更改或更改(this)时,它都会抛出一个段错误。

它还说 (this) 不是空的(这似乎是唯一一个不抛出 seg 错误的)

这里是调用更多信息的方法的代码。希望这里的人能给我一些关于这里发生的事情的见解。

void insert(iterator position, const value_type& in)
{
    // If inserting at the front, just change the head to a new Node
    if (position == this->head) 
        this->head = new Node<value_type>(in);
    else
    {
        Node<value_type>* node = this->head;
        // iterate to the position of "position".
        for (; node->next != position.node; node = node->next);
        node->next = new Node<value_type>(in);
    }
    // This is here to put back all the old data into it's correct position.
    // I was having way too much with keeping the integrity of the data
    // while inserting into the middle of the list, so I created this little hack.
    for (iterator it = position; it != this->end(); ++it)
    {
            Node<value_type> *node = this->head;
            for (; node->next != NULL; node = node->next);
            node->next = new Node<value_type>(it.node->data);
    }
}

// Insert at end
void push_back(value_type in)
{
    this->insert(this->end(), in);
}

unsigned size()
{
    if (this->empty()) return 0;
    unsigned i = 0;
    for (iterator it = this->begin(); it != this->end(); ++it, ++i);
    return i;
}

bool empty() const { return this->head == NULL; }

【问题讨论】:

    标签: c++ list segmentation-fault containers copy-constructor


    【解决方案1】:

    在我写完这篇文章后几乎立即就解决了问题。

    我所要做的就是首先将 head 分配给 NULL

    List(List<value_type>& list)
    {
        this->head = NULL;
    
        for (iterator it = list.begin(); it != list.end(); ++it)
            this->push_back(*it);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-07
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      相关资源
      最近更新 更多