C ++:对象的向量与向新对象的指针的向量?

编程入门 行业动态 更新时间:2024-10-22 08:29:41
本文介绍了C ++:对象的向量与向新对象的指针的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻求通过编写示例软件渲染器来提高我的C ++技能。它需要由3d空间中的点组成的对象,并将它们映射到2d视口,并为视图中的每个点绘制不同大小的圆。哪个更好:

I am seeking to improve my C++ skills by writing a sample software renderer. It takes objects consisting of points in a 3d space and maps them to a 2d viewport and draws circles of varying size for each point in view. Which is better:

class World{ vector<ObjectBaseClass> object_list; public: void generate(){ object_list.clear(); object_list.push_back(DerivedClass1()); object_list.push_back(DerivedClass2());

或...

class World{ vector<ObjectBaseClass*> object_list; public: void generate(){ object_list.clear(); object_list.push_back(new DerivedClass1()); object_list.push_back(new DerivedClass2());

?将在第二个例子中使用指针来创建新对象,打败使用向量的点,因为向量在第一个示例中自动调用DerivedClass析构函数,但不在第二个示例中。当使用向量时,指向新对象的指针是否必要,因为只要使用它们的访问方法,它们自己处理内存管理?现在让我们说我在世界上有另一个方法:

?? Would be using pointers in the 2nd example to create new objects defeat the point of using vectors, because vectors automatically call the DerivedClass destructors in the first example but not in the 2nd? Are pointers to new objects necessary when using vectors because they handle memory management themselves as long as you use their access methods? Now let's say I have another method in world:

void drawfrom(Viewport& view){ for (unsigned int i=0;i<object_list.size();++i){ object_list.at(i).draw(view); } }

调用时,将为每个对象运行绘制方法在世界名单上。让我们说,我想让派生类能够有自己的版本的draw()。

When called this will run the draw method for every object in the world list. Let's say I want derived classes to be able to have their own versions of draw(). Would the list need to be of pointers then in order to use the method selector (->) ?

推荐答案

你不会得到什么

class World{ vector<ObjectBaseClass> object_list; public: void generate(){ object_list.clear(); object_list.push_back(DerivedClass1()); object_list.push_back(DerivedClass2());

会发生什么叫做对象切片。你将得到一个ObjectBaseClass的向量。

What is going to happen is called object slicing. You will get a vector of ObjectBaseClass.

为了使多态性工作你必须使用某种指针。在boost或其他库中可能有一些智能指针或引用可以使用,并使代码比第二个建议的解决方案更安全。

To make polymorphism work You have to use some kind of pointers. There are probably some smart pointers or references in boost or other libraries that can be used and make the code much safer than the second proposed solution.

更多推荐

C ++:对象的向量与向新对象的指针的向量?

本文发布于:2023-07-30 00:31:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1244979.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   对象   指针   向新

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!