没有指针的C ++多态 [英] C++ polymorphism without pointers

查看:121
本文介绍了没有指针的C ++多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个基类 Animal 与虚函数和一些派生类( Cat Dog 等)。真正的派生类包含4-8字节的数据。我想要存储一个 std :: list< Animal> ,它实际上包含派生对象的项目。我想避免使用new在堆上创建许多小对象。

Suppose that I have a base class Animal with virtual functions and some derived classes (Cat, Dog, etc.). The real derived classes contain 4-8 bytes of data. I want to store a std::list<Animal> which actually contains items which are derived objects. I want to avoid the creation of many small objects on the heap using new.

有没有任何设计模式可以用来实现这一点?

Is there any design pattern which can be used to achieve this?

编辑:我的想法实现此


  1. 创建 std :: deque< Cat> std :: deque< Dog> ,...; store std :: list< Animal *> 其中包含来自 deques 我使用 std :: deque ,因为我想它有一个很好的内存管理与大块的对象;

  1. create std::deque<Cat>, std::deque<Dog>, ...; store std::list<Animal*> which contains pointers from the deques; I use the std::deque because I suppose that it has a good memory management with chunks of objects;


推荐答案

最终,不。

多态只适用于非值类型:引用和指针。因为引用只能绑定一次,你不能真正地在标准容器中使用它们。

Polymorphism only works with non-value types: references and pointers. And since references can only be bound once, you cannot really use them in standard containers. That leaves you with pointers.

你在错误的一端攻击这个问题。如果你担心分配大量小对象的开销(我假设这是一个合理的问题,也就是说,你有实际的分析数据或足够的经验来知道这是一个问题对于您的特定应用程序),那么您应该修复 。更改为这些对象分配内存的方式。 make a small allocation heap or something。

You're attacking the problem at the wrong end. If you are concerned about the overhead of allocating lots of small objects (and I'm assuming that this is a legitimate concern. That is, you have actual profiling data or sufficient experience to know it is a concern for your specific application), then you should fix that. Change how you're allocating memory for these objects. Make a small allocation heap or something.

不可否认,C ++ 0x之前的分配器在这方面有点欠缺,因为它们必须是无状态的。

Admittedly, pre-C++0x's allocators are somewhat lacking in this regard, since they have to be stateless. But for your purposes, you should be able to deal with it.

从您的编辑中删除:

这是一个可怕的想法。在任何位置从 std :: deque 擦除,但开头或结尾会使<$ c>中的每个 $ c> std :: list 。

That is a terrible idea. Erasing from a std::deque at anywhere but the start or end will invalidate every pointer in your std::list.

然而,具有用于不同种类的对象的所有这些不同的存储器块似乎违背了整个继承点。毕竟,你不能只是写一个新类型的 Animal 并把它放到 std :: list ;你必须为它提供内存管理。

Given your comment, this idea is functional. However, having all of these different memory blocks for different kinds of objects seems to go against the whole point of inheritance. After all, you can't just write a new type of Animal and slip it into the std::list; you have to provide memory management for it.

你确定基于继承的多态性是你在这里需要的吗?您确定其他一些方法不会正常工作吗?

Are you sure that inheritance-based polymorphism is what you need here? Are you sure that some other methodology would not work just as well?

这篇关于没有指针的C ++多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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