C++ array and polymorphic objects

Started by
29 comments, last by ApochPiQ 12 years ago
So yeah a array of pointers would be the solution, but I was wondering if a single array type would work and I am getting a NO loud and clear here...[/quote]

I'm not really sure about goal, but for code example given above, raw array or vector both behave almost identically, except that array has fixed size of 1000 elements and no count, which needs to be maintained separately.

If your question is about polymorphism, then yes, pointers to polymorphic objects can be stored in array, no problems there.

I think this would be a more concise example....[/quote]

That works, no problems here.

Either array or vector, you're storing pointers (to something). Pointers are all of equal size, determined by compiler settings and don't differ between types (with potential exception for member function pointers).


What is trickier is storing polymorphic objects by value (vector<Obj3D>, note the missing *). That is possible too, it's just much more complicated and can either improve or decrease efficiency.
Advertisement

[quote name='Dave' timestamp='1334825747' post='4932733']
There isn't anything wrong with using raw arrays or manual memory management at all. I would strongly suggesting thinking about whether you really need to use anything from the standard library or boost before you actually do.


I would consider this dangerous and unhelpful advice. The reverse should be true: Unless using something from the standard library or Boost is going to cause significant, documentable problems you should use those tools. Admittedly, there are situations where neither of those two will be helpful (like working on some platform with a horribly suboptimal compiler or under extreme resource constraints where you have to count each byte) but this is not the usual case.
[/quote]

If you're using STL you're usually also new'ing things up all over the place in your code. You're probably even using smart pointers now because you have no idea where things are getting cleaned up. Automatically using magic solutions like STL and Boost without any real thought (and i'm not saying this is you specifically) causes you to relax about how you are structuring and processing data.

If you organise your application well enough your memory layout will drive the architecture and you will find that you won't need STL for nearly anything.
I'm still not 100% sure of the "problem", but one idea is to have an array of values for each of the different types.

const int numCubes = /* ... */;
const int numMeshes = /* ... */;
cosnt int numSpheres = /* ... */;

Cube cubes[numCubes];
Mesh meshes[numMeshes];
Sphere spheres[numSpheres];

initCubes(cubes, numCubes);
initMeshes(meshes, numMeshes);
initSpheres(spheres, numSpheres);


One way to do this is to build a big array of pointers to these objects. The advantages here are that each group of objects is contiguous. The disadvantage here is that you have to maintain the second array, which when you're dealing with dynamic numbers of objects becomes more complicated.

Obj3D *objects[numCubes + numMeshes + numSpheres];
int index = 0;
for( int i = 0 ; i < numCubes ; ++i)
{
objects[index] = &cubes;
++index;
}
// Copy meshes and spheres too...

// Later
for(auto object : objects)
{
object->Draw();
}



A second approach is to keep the arrays separate, and write generic functions for handling common routines.

template<class T>
void draw(T *objects, int count)
{
for(int i = 0 ; i < count ++i)
{
objects.Draw();
}
}

draw(cubes, numCubes);
draw(meshes, numMeshes);
draw(spheres, numSpheres);

A side effect of this approach is that you are no longer making virtual calls to Draw(), the exact type is known by the compiler.

The former approach is quite convenient to write code for (once the array is correctly maintained), but uses more memory. The latter option can complicate certain algorithms that need to work across the entire data set, and results in more code generated. For example, "get the closest Obj3D" now needs to be multi-stage algorithm, instead of a simple search of one big array. Drawing transparent objects after the others, in the correct Z order, is simpler in the former case (sort the array by transparency enabled, and sub-sort the transparent portion by Z index).

Both options suffer complexity when the number of derived types get large.
I wouldn't recommend hand-coding a dynamic array without an utterly compelling reason. My post was actually written a few hours ago, before the latest replies. I'd use std::vector<> as a dynamic array, writing the equivalent by hand is a good way to get additional bugs and, unless you know what you are doing, your program will actually end up slower too.

I wouldn't recommend hand-coding a dynamic array without an utterly compelling reason. My post was actually written a few hours ago, before the latest replies. I'd use std::vector<> as a dynamic array, writing the equivalent by hand is a good way to get additional bugs and, unless you know what you are doing, your program will actually end up slower too.


You shouldn't really need dynamic arrays, is my point. Not if you've thought things through.
It's nice to know you deny the existence of C++ programs that work with text. It helps put your bad advice into context.

[quote name='rip-off' timestamp='1334847545' post='4932810']
I wouldn't recommend hand-coding a dynamic array without an utterly compelling reason. My post was actually written a few hours ago, before the latest replies. I'd use std::vector<> as a dynamic array, writing the equivalent by hand is a good way to get additional bugs and, unless you know what you are doing, your program will actually end up slower too.


You shouldn't really need dynamic arrays, is my point. Not if you've thought things through.
[/quote]

struct Pixel
{
unsigned char r;
unsigned char g;
unsigned char b;
};

struct Image
{
int width;
int height;
// Oh shiz, what now?! Obviously I haven't thought things through if I want to have images with varying sizes.
// I was going to create an std::vector<Pixel> (or Pixel* if I was using C), but I guess I just need to "think things
// through" more so I don't have to use dynamic arrays, because obviously I'm doing it wrong if I use them! I
// guess the better option would be to create a Pixel[100000]. Yes, that sounds like a better solution. That way
// I can only support images with 100000 pixels, and even if I have an 8x8 pixel image, I really think all 100000
// pixels are necessary. Yes, this is better.
};

[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

It's nice to know you deny the existence of C++ programs that work with text. It helps put your bad advice into context.


Or you could just give yourself some good old max sizes.
...
I appreciate this advice, but I'd probably still advise people first learn to use STL/RAII/etc (before going back to keeping it simple) wink.png

Personally, I learned C++ first in a "c with classes" way, then pure C++ with STL/boost/metaprogramming, then back to something more like "c++ with structs".

e.g.
My current game only has 1 [font=courier new,courier,monospace]malloc[/font] (and some [font=courier new,courier,monospace]new[/font]'s in middleware bindings) that places a large address range into a [font=courier new,courier,monospace]scopestack[/font], in which you can allocate objects or other [font=courier new,courier,monospace]scopes[/font]. It's still proper C++ with reliable constructors/destructors/etc and RAII, but instead of the "smart pointer" type only maintaining the lifetime of 1 link, it is instead a container of links (or actually, a linked-list of destructors to call when the scope is unwound). When using POD types, allocation and deallocation are just pushing/popping from a stack of bytes (almost free, like regular stack/local allocation), but with a 'scope' object representing their lifetime.

This makes "dynamic memory allocation" as easy and predictable (bug-friendly) as regular C/C++ stack allocation rules, without ever worrying about using the heap ([font=courier new,courier,monospace]new[/font]/[font=courier new,courier,monospace]malloc[/font]). It also means that you can use raw arrays and pointers much more safely and easily than with C++ smart pointers. Raw "unsafe" code can really be easier and simpler in the right conditions -- IM, the right way to learn about those conditions is to first learn the standard (STL) way to manage things, and then see what junk you can strip out once you grok it.

To illustrate, if a Foo class had to maintain a Bar member using dynamic allocation:
In C with classes:class Foo // verbose, explicit
{
public:
Bar* m;
void Init() { m = (Bar*)malloc(sizeof(Bar)); Bar::Init(m); }
void Deinit() { free(m); }//oh damn this verbosity, I forgot to call Bar::Deinit(m)
};
Foo* test = (Foo*)malloc(sizeof(Foo));
Foo::Init(m);
Foo::Deinit(m);
free(test);
In basic C++:class Foo : NonCopyable //copy constructor/assignment operator need to be implemented if copyable (rule of three)
{
Bar* m;
public:
Foo() m(new Bar) {}
~Foo() { delete m; }
};
Foo* test = new Foo;
delete test;
In modern C++:class Foo
{//N.B. actually smart_pointer, auto_ptr, etc
smart_pointer<Bar> m;// handles destructor and copy (via reference counting)
public:
Foo() m(new Bar) {}
};
smart_pointer<Foo> test( new Foo );
With a simple stack allocator:class Foo
{
Bar* m;
public:
Foo(Scope& a) m(myNew(a,Bar)) {}//member should have same scope as parent, no need for destructor or copy
// copies are weak (possibly dangling, not ref-counted) pointers just like the basic C++ / C examples, so should only be passed to objects *closer to the top of the stack*.
};
Stack stack( malloc(GB(1)), GB(1) );
Scope a( stack );
Foo* test = myNew(a, Foo)(a);//increments a stack alloc, constructs, adds destructor to scope

//@ Cornstalks -- struct Image // Oh shiz, what now?!
struct Image
{
int width, height;
int size() {return sizeof(Image) + sizeof(pixel)*width*height;}
pixel* begin() { return (pixel*)(this+1); }
pixel* end() { return begin() + width*height; }
}
Image* test = myAlloc(a, Image::size());//increments a stack alloc, valid until 'a' is destructed

[quote name='Dave' timestamp='1334848546' post='4932817']
[quote name='rip-off' timestamp='1334847545' post='4932810']
I wouldn't recommend hand-coding a dynamic array without an utterly compelling reason. My post was actually written a few hours ago, before the latest replies. I'd use std::vector<> as a dynamic array, writing the equivalent by hand is a good way to get additional bugs and, unless you know what you are doing, your program will actually end up slower too.


You shouldn't really need dynamic arrays, is my point. Not if you've thought things through.
[/quote]

struct Pixel
{
unsigned char r;
unsigned char g;
unsigned char b;
};

struct Image
{
int width;
int height;
// Oh shiz, what now?! Obviously I haven't thought things through if I want to have images with varying sizes.
// I was going to create an std::vector<Pixel> (or Pixel* if I was using C), but I guess I just need to "think things
// through" more so I don't have to use dynamic arrays, because obviously I'm doing it wrong if I use them! I
// guess the better option would be to create a Pixel[100000]. Yes, that sounds like a better solution. That way
// I can only support images with 100000 pixels, and even if I have an 8x8 pixel image, I really think all 100000
// pixels are necessary. Yes, this is better.
};


[/quote]

This is not a valid point.

This topic has been discussing the use of std::vector of c-style arrays, for your image scenario you don't need a std::vector anyways so i'm not sure what your point is. Dynamic allocation is not the discussion here.

This topic is closed to new replies.

Advertisement