不同节点的相同地址
the same addresses of different nodes
我尝试编写一个双向列表。我必须使用重载运算符 ([] 和 +=)。[] - 对给定节点的访问。+= - 将节点添加到我的列表中。我写了这些方法,看起来不错,但它不起作用,我不知道为什么。
以下是我代码的核心行:
//********************************************************
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
)。
在对象超出范围并被销毁后使用/访问对象是未定义的行为,因此通常会崩溃或其他行为异常。
相关文章:
- 反向给定链表中的K节点
- 将数组的地址分配给变量并删除
- 空基优化子对象的地址
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- Boost Graph Library,修复节点大小
- C++中是否有一个函数可以为您获取指向该节点的所有指针的地址空间
- 如何在NS3中设置节点的IP地址和数据?
- 在C++中设置节点的内存地址
- C++:尝试将新节点添加到链表会产生"线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x0)"错误
- 不同节点的相同地址
- 存储链接列表节点地址
- 通过池分配器中的内存地址访问可用列表节点时出现问题
- 为节点分配指针地址
- 获取类型为"节点"的临时对象的地址
- 正在访问指针地址处的节点
- 如何返回节点的地址
- 在第三次调用中,当地址因本地作用域而被销毁时,temp2->next 如何能够访问第二个节点的地址?
- 复制构造函数双链接列表中的头节点和尾节点的地址不正确
- 给定链表中的节点地址,获取节点的地址