I was wondering if it is possible to swap the data from
from a vector :
vector (item) v__
into
vector (item *) v__ptrs
( a vector of the same class but with pointers)
to avoid calling new or using push_back…
I have a vector of class pointer :
vector (ItemGeneric * ) items
and I want to use the fastest way possible to allocate and initialize it
if it’s a normal : vector (ItemGeneric ) items (not pointers)
and I call items.resize(10000)
it’s super fast
But in my case is a vector to pointers so… I need to either use new after resize
items[i]= new ItemGeneric
or… I was thinking
if I use a temporary normal stack vector in the scope I am doing the allocation
resize it
and then call swap, is it possible to call swap
and transfer/move/swap the items in two non identical vectors?
like from vector (item) v__ to vector (item *) v__ptrs???
and then clear the vector of pointer or just let it be… is such a thing possible?
or any other ways to allocate a lot of stuff into a vector of pointers??
The straightforward way to convert a vector of objects to a vector of pointers is:
std::vector<ofRandomType> source;
std::vector<ofRandomType*> target;
for(auto it = source.begin(); it != source.end(); it++) {
target.push_back(&(*it));
}
That said, if you convert these objects to pointers, you’ll need to deal with the ‘ownership’ of the pointers, and which class is responsible for deleting all of them. You can possibly avoid this by turning everything into an ofPtr, which is a wrapper around std::shared_ptr.
nothing in a vector is really created in the stack, all the memory is allocated in the heap, the difference is that when you have a vector of objects all the memory is allocated as one big chunck of contiguous memory, while when allocating a vector of pointers, the vector allocates memory for all the pointers but you have to then allocate memory for each pointed object one by one.
the first option, a vector of objects, is faster not only to create but also to access so it’s always preferable. usually you want a vector of pointers only if you need polymorphism, if you want to put in the vector objects of different classes with a common base. or if the objects you want to store can’t be copied (although even that is allowed in c++11 in most cases)
do we have a way in OF to stop & remove all event listeners at once?
…I have a class that includes another class that does threading behind the scenes plus I added a couple of event listeners
plus raw pointers left and right
so as it is now i might need to delete things after listeners have been removed or wait for threats etc
it would be nice if you could allocate pointers initialized instead of simple memory addresses so that it is as fast as you do "in the stack ".
so that you have best of both worlds and later on you have the option to release after you waited for something to finish etc…
…and all that without c++ 11