Quote:Original post by StratBoy61
Hello,
To me, the problem comes from the fact that you are storing into your std::vector a structure that was allocated on the stack : The vector will then have to create a copy of this structure in order to keep track of it.
In your scenario, your structure will be allocated once in your function's stack, then another time by your vector, and then freed when you exit your function.
As you mentioned, a better approach might be to store the structures' pointer into your std::vector --rather than the structure themselves. I must admit that I do not understand when you say "(...)this still quite slow, as you are having to duplicate the object data and then delete the temporary array afterwards." though...
To me, you do not duplicate anything if you proceed like this:
MyObject *object = malloc...
std::vector<MyObject *> m_object_list;
m_object_list.push_back(object);
(...)
free(object);
The only things you can duplicate are the MyObject pointers values...
My two cents.
StratBoy61
Oh my god, please tell me you're kidding.
0) The duplication the OP was talking about would arise from reading into a single allocated chunk, and then copying the chunk into the vector's memory allocation.
1) Previous posters illustrated that you can fread
directly into the vector's memory allocation, which is guaranteed to be contiguous.2) This is C++; we don't use malloc() any more.
3) You're going to add, per object, an extra pointer's worth of memory, and also totally destroy compatibility if he actually needs a vector of actual structures (quite likely if working with a graphics API).
4) Your solution to avoiding a copy from the stack to an already-allocated chunk of memory, is to
dynamically allocate a tiny chunk, write to the chunk directly, and set a pointer in the already-allocated chunk of memory to the new allocation. That's actually going to be much slower, and cause huge amounts of fragmentation.
5) You free 'object', which rather suggests freeing immediately, which would be a huge mistake.
Quote:Original post by Agony
If the object is plain-old-data, and doesn't contain pointers, and you'll never have to worry about endianness, and your struct padding is consistent, and you don't mind casting the structure's data members in stone that much more (consider what happens if you want to add a cache for a frequently calculated value) I suppose it's okay, but it just sets my warning alarm off.
[smile]