创建指针列表的正确范例是什么? [英] What is the proper paradigm of creating a list of pointers?

查看:75
本文介绍了创建指针列表的正确范例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己 漫不经心地编写了一些类,这些类添加了指向对象的指针,这些对象后来被销毁到列表中,这导致了很多段错误,但是问题是有时我只是可以't 提出了一个比存储指针列表更好的解决方案.在我看来,似乎没有一种简单的方法可以在C ++中存储无法复制的临时对象".我缺少有效地执行此操作的范例吗?

例如,我将有一个看起来像这样的类:

class MyClass
public:
   std::vector<OtherClass *> other_objects;
   void method() {
      OtherObject other_object = create_other_object();
      other_objects.push_back(&other_object);
   }

您可能要执行此操作的原因之一是因为您在其他地方使用了other_objects(作为其他函数的参数),并且无法复制OtherObject实例(如果OtherObject复制构造函数是私有的,则可能会发生这种情况)例如).

当然,一旦您尝试在代码中的其他地方使用other_objects,每个指针指向的内存将被销毁.

我写了很多Python代码,并且经常使用这种结构非常,其中一种方法用仅存在于该方法范围内的对象填充一个可迭代对象.有没有办法在C ++中有效地做到这一点?我可以做自己的内存管理来使方法中的临时对象保持活动状态,超出方法范围吗?

解决方案

在C ++中创建指针列表的正确范例是什么?

合并 std::list (或其他一些容器)和一些智能指针类(请参见此处 ),例如 std::shared_ptr 原始指针并更喜欢智能指针. 内存管理是一个棘手的话题.如果您阅读了垃圾收集(例如引用计数-有些人将其视为GC的原始形式). 圆形引用很难处理(请注意 C ++编程书,并参考一些内存模型.

请注意五个规则.

在某些操作系统和/或C ++实现中,您可以找到工具,例如 valgrind 地址清理器 nofollow noreferrer> Clang 或 GCC ,这应该有助于您进行调试,然后避免使用内存泄漏(详细信息取决于编译器和/或操作系统).在少数几种情况下(可能只有少数几种),您可能会考虑使用垃圾收集器库(例如 Boehm的GC ,请参见大米定理让我相信没有一个可以管理内存.您的里程会有所不同.您需要精确地了解您的内存管理以及其他编程约束和目标,并做出自己的权衡.请参阅Norvig的意见.有 无银弹 .


PS. C ++是一种极其困难的编程语言.准备花费很多时间(几年而不是几个月;也许是几十年)并努力学习它.为了获得启发,还请看一些用C ++编写的,编写得很好的免费软件的源代码.我并没有声称自己是C ++的高手(即使我的日常工作是有关设计和实现一些静态源代码的分析器).我相信在这个星球上可能只有几十个(或几百个)C ++大师,而我不在其中.

PPS.我有偏见,但我建议在您的开发机上使用 Linux来学习C ++编程,这恰恰是因为它具有许多有用的工具

I find myself so frequently thoughtlessly writing classes that add pointers to objects which are later destroyed to lists, which results in a lot of segfaults, but the problem is that sometimes I simply can't come up with a better solution than to store a list of pointers. It does my head in that there doesn't seem to be a simple way of just "storing temporary objects that you can't copy" in C++. Is there a paradigm I'm missing on how to do this effectively?

For example, I'll have a class that looks something like this:

class MyClass
public:
   std::vector<OtherClass *> other_objects;
   void method() {
      OtherObject other_object = create_other_object();
      other_objects.push_back(&other_object);
   }

One reason you may want to do this is because you use the other_objects elsewhere (as arguments to other functions) and you can't copy OtherObject instances (which could happen if the OtherObject copy constructor was private for example).

Of course, once you attempt to use other_objects elsewhere in code, the memory each pointer points to will have already been destroyed.

I write a lot of Python code, and I use this sort of structure very often, where a method populates an iterable with objects that exist solely in the scope of the method. Is there a way to do this effectively in C++? Could I do my own memory management to keep the temporary objects in the method alive beyond the scope of the method?

解决方案

What is the proper paradigm of creating a list of pointers in C++?

Combine std::list (or perhaps some other container) with some smart pointer class (see here) such as std::shared_ptr or std::unique_ptr.

As a rule of thumb (sometimes wrong) avoid raw pointers and prefer smart pointers. Memory management is a tricky topic. If you read some book on garbage collection (e.g. the GC handbook) you'll learn the relevant concepts, terminology and techniques (and these apply even with manual memory management such as reference counting - which some people view as a primitive form of GC). Circular references are painful to handle (be aware of weak references, e.g. std::weak_ptr).

It would take a lot of space and time to explain all this in details (and I don't have time or motivation or even all the skills for that) here. Read a good C++ programming book and refer to some C++ reference (and later perhaps to the C++11 standard n3337 or something newer). Be aware that the memory model of C++ is difficult to understand (for anyone).

Be aware of the rule of five.

On some operating systems and/or C++ implementations, you can find tools, such as valgrind or the address sanitizer of Clang or GCC, which should help you to debug then avoid memory leaks (details are compiler and/or OS specific). And in some few cases (probably a minority of them), you might consider using a garbage collector library (such as Boehm's GC, see this, or MPS).

Is there a way to do this effectively in C++?

I don't know of any efficient, universal and simple way (and Rice's theorem make me believe there cannot be one) to manage memory. Your mileage will vary. You need to precisely understand your memory management and other programming constraints and objectives and make your own trade-offs. See Norvig's opinion. There is No Silver Bullet.


PS. C++ is an extremely difficult programming language. Prepare yourself to spend a lot of time (years, not months; perhaps decades) and efforts to learn it. Look also, for inspiration, into the source code of some well written free software coded in C++. I don't claim to be a C++ master (even if my daily job is about designing and implementing some static source code analyzers for it). I believe that there might be only a few dozens (or perhaps a few hundreds) of C++ masters on this planet, and I am not among them.

PPS. I am biased, but I recommend using Linux on your development machine to learn C++ programming, precisely because it has lots of useful tools.

这篇关于创建指针列表的正确范例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆