无法应对错误(析构函数会破坏所有内容)

时间:2013-04-19 15:07:09

标签: c++

我遇到了这个问题:

No source available.
Call stack location: lab5.exe! Counter:: 'scalar deleting destructor'() + 0x2b bytes.

我构建了一个链表。

counter.h

class Counter{
    private:
        char* m_pStr; 
        unsigned int m_nOwners; 
        Counter* pNext;         
        static unsigned int m_curCounters;
        static Counter* Head;   
...

counter.cpp

Counter* Counter:: Head = new Counter();
unsigned int Counter:: m_curCounters = 0;

Counter:: ~Counter(){
    if  (this == Head){
        Head = Head->pNext;
    }
    else{
        Counter* current = Head->pNext;
        for (int i = 0; i < m_curCounters; i++){
            if (current->pNext == this){
                            // Searching for counter, with next one equal this.
                current->pNext = this->pNext;
                break;
            }
            current = current ->pNext;
        }
    }
    m_curCounters--;
    delete[] this->m_pStr;
}

关闭大括号会导致错误。在图片中:一步将我与错误屏幕和错误本身分开。

Screenshot 1 Screenshot 2 Screenshot 3

P.S。禁止使用载体。

1 个答案:

答案 0 :(得分:2)

您的课程需要遵循 Rule of Three 你需要提供一个复制构造函数&amp;复制赋值运算符,用于执行动态分配的数据成员的深层副本。

或者,您可以使用智能指针而不是原始指针。这将为您节省所有明确的手动内存管理。

此外,您最好用char *替换std::string