C ++:对象的向量与向新对象的指针的向量? [英] C++: Vector of objects vs. vector of pointers to new objects?

查看:174
本文介绍了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 ++:对象的向量与向新对象的指针的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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