首页 > 解决方案 > C++中链表和指针的要点

问题描述

老实说,我需要帮助来理解这一点。我是一名计算机科学专业的学生,​​我在这些主题上遇到了巨大的心理障碍,因为我无法理解为什么这很重要/为什么我们如此重视这一点。

就指针而言,当您可以通过引用传递所有内容时,为什么还要指向对象或变量地址?我们不能通过引用而不是使用指针来有效地传递这些东西是有原因的吗?

另外,为什么在 C++ 中没有自动删除指针或专门删除堆上的东西?为什么不像其他所有内容一样删除?为什么它不像其他所有东西一样集成到 C++ 中?

标签: c++listpointerslinked-listreference

解决方案


The point of going through these exercises is not to learn how to make linked lists per-se, but to learn how to solve problems and implement code according to designs. Don't forget that whatever you do in class is pretty much junk by definition, you're not going to roll that code out in an application, it's just an exercise for learning. You create these programs to understand and practice, not to create solutions.

The code you write to learn and explore is radically different from the code you write to actually solve problems. When trying to solve problems stay focused on the solution, try to avoid getting caught up with trying new things just for the sake of having fun. When learning try to avoid going too quickly to the solution, instead explore other approaches and weigh their advantages and drawbacks.

Now as to why C++ takes that approach, every language has a philosophy that dictates its design. In C++ that means you are 100% in charge of memory management, you have complete control. While this gives you incredible latitude in how you go about doing that, it also means it's an enormous responsibility.

If you want garbage collection you can get it, but you have to ask and you have to use things like the Standard Library containers or pointer wrappers.

A lot of modern C++ revolves around avoiding memory management altogether by focusing on a design that makes objects cheap to copy, by passing in things by reference whenever possible, and by leveraging the tools provided by the Standard Library to make manual memory management largely irrelevant. new is something you do out of desperation, not by design.

For more insight you might want to invest in some books that focus on applying C++ strategically.


推荐阅读