简体   繁体   English

指针和双向链表

[英]Pointers and doubly-linked list

I am currently on chapter 17 of "Programming: Principles and Practice using C++", and I came across a code on doubly-linked list. 我目前在“编程:使用C ++的原理和实践”的第17章,并且遇到了双向链表上的代码。 Questions have been asked on this set of codes before for (eg Member access in a doubly-linked list ), however I have a question that wasn't asked/answered. 之前曾有人问过这组代码问题(例如,双向链接列表中的成员访问权限 ),但是我没有被问到/回答。

The code basically arranges "Freya" as a predecessor of "Odin", and makes "Odin" a predecessor of "Thor", and the other way round as successors. 该代码基本上将“ Freya”安排为“ Odin”的前身,并使“ Odin”成为“ Thor”的前身,反之亦然。 The code is as follows: 代码如下:

struct Link {
string value;
Link* prev;
Link* succ;
Link(const string& v, Link* p = nullptr, Link* s = nullptr)
    : value(v), prev(p), succ(s) {}
};

int main()
{
    Link* norse_gods = new Link{ "Thor", nullptr, nullptr };
    norse_gods =       new Link{ "Odin", nullptr, norse_gods };

    norse_gods->succ->prev = norse_gods;
    norse_gods =       new Link{ "Freya", nullptr, norse_gods };

    norse_gods->succ->prev = norse_gods;

}

What I would like to know is that why the code: 我想知道的是为什么代码:

norse_gods =       new Link{ "Odin", nullptr, norse_gods }

is able to point to the old address: new Link{ "Thor", nullptr, nullptr } , and making Thor the successor of Odin since norse_god should already be pointing to the new address: new Link{ "Odin", nullptr, norse_gods } ? 能够指向旧地址: new Link{ "Thor", nullptr, nullptr } ,并使Thor成为Odin的后继者,因为norse_god应该已经指向新地址: new Link{ "Odin", nullptr, norse_gods } Is there some order or evaluation or concept that I am missing out? 我缺少一些命令,评估或概念吗?

The evaluation is first done on the right side and then operator= kicks in and does the assignment. 首先在右侧进行评估,然后operator=进入并执行分配。 This is caused by the priority of operator= . 这是由operator=的优先级引起的。 See C++ Operator Precedence . 请参阅C ++运算符优先级

At the first line of main , you are creating a Link with name "Thor" and pointing norse_gods to it. main的第一行,您将创建一个名为“ Thor”的Link ,并将norse_gods指向该Link

At the second line, you are creating a Link with name "Odin" and a successor norse_god , which is still pointing at Thor at the moment of construction. 在第二行中,您将创建一个名为“ Odin”和后继项norse_godLink ,该Link在构建时仍指向Thor。

After that, norse_gods is updated to point to "Odin". 此后, norse_gods将更新为指向“ Odin”。

This behavior is normal for C-like languages. 对于类似C的语言,此行为是正常的。

The expression on the right-hand side is evaluated first. 首先评估右侧的表达式。 This evaluates taking the old value of norse_gods . 这将评估使用norse_gods的旧值。 Once this evaluation is complete, the assignment is done, and the reference to the newly created object is assigned to norse_gods . 评估完成后,便完成分配,并将对新创建对象的引用分配给norse_gods

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM