不同节点的相同地址

the same addresses of different nodes

本文关键字:地址 节点      更新时间:2023-10-16

我尝试编写一个双向列表。我必须使用重载运算符 ([] 和 +=)。[] - 对给定节点的访问。+= - 将节点添加到我的列表中。我写了这些方法,看起来不错,但它不起作用,我不知道为什么。

以下是我代码的核心行:

//********************************************************
CLista::CNode* CLista::operator[](int i_index)
{
int i_help = 0;
CNode* c_result = &c_root;
while(i_help < i_index)
{
    c_result = c_result->getNext();
    i_help++;
}
return c_result;
}
//*********************************************************
void CLista::operator+=(void* pv_object)
{
if(i_numNodes == 0)
{
    c_root = CNode(pv_object);
}
else
{
    CNode c_new = CNode(pv_object);
    CNode* c_help = this->operator[](i_numNodes - 1);
    c_new.setPrevious(c_help);
    (*c_help).setNext(&c_new);
}   
i_numNodes++;
 }
 int _tmain(int argc, _TCHAR* argv[])
 {
CLista list = CLista();
string s1 = string("first");
void* wsk1 = &s1;
string s2 = string("second");
void* wsk2 = &s2; 
string s3 = string("third");
void* wsk3 = &s3; 
list += wsk1;
list += wsk2;
list += wsk3;

void* res1 = (*list[0]).getObject();
void* res2 = (*list[1]).getObject();
void* res3 = (*list[2]).getObject();
cout << "res1: " << res1 << endl;
cout << "res2: " << res2 << endl;
cout << "res3: " << res3 << endl;
cout << "wsk1:" << wsk1 << endl;
cout << "wsk2:" << wsk2 << endl;
cout << "wsk3:" << wsk3 << endl;
   }

这是标题:

class CLista
{
public:
    class CNode
    {
        public:
            CNode(void)
            {
                pc_next = NULL;
                pc_previous = NULL;
            }
            CNode(void* pv_object)
            {
                pc_next = NULL;
                pc_previous = NULL;
                this->pv_object = pv_object;
            }
            CNode* getNext(){return pc_next;};
            CNode* getPrevious(){return pc_previous;};
            void*  getObject(){return pv_object;};
            void setNext(CNode* pc_next);
            void setPrevious(CNode* pc_previous);
        private:
            CNode* pc_next;
            CNode* pc_previous;
            void*  pv_object; // czy to jest dobrze?
    };
    CNode c_root;
    int i_numNodes;
public:
    CLista(void);
    ~CLista(void);
    CNode* operator[](int index);
    void operator+=(void* object);
};

当我将第三个元素添加到列表中然后检查它时,这是一个奇怪的问题:res2 和 res3 的地址是相同的。

operator += 函数中,创建一个名为 c_new 的本地CNode,并将其链接到链表中。 当作用域结束时(在函数返回之前发生),该局部被破坏,使列表悬而未决(指向不再有效的CNode,其内存即将重用于其他一些局部变量,例如下次调用函数时创建的下一个c_new)。

在对象超出范围并被销毁后使用/访问对象是未定义的行为,因此通常会崩溃或其他行为异常。