I have a class cnList which stores a flexible number of items. This list must later be converted to a cnArray object. The list class already implements a method cnArray cnList::toArray() const.
But as you can see, it returns an object, not a reference nor a pointer. But what I have to do after converting the list to an array, is to store this array for later use in a class member, this means, I need to have a pointer to that cnArray object.
Now, the actual problem is, simply using the arrays adress is not an option because it gets freed after the method I’m currently in, ends.
Can I somehow “convert” this object to a pointer and the object isn’t freed anymore ?
Sure, I could copy all entries from the object-array to a pointed-array, but thats not what I want, since it’s not very efficient.
I am aware of the fact that I could implement a method in cnList that returns a pointer to a cnArray object, but I’d like to know if there is around this.
You can allocate a new cnArray from the heap, constructed from the return value of
toArray. If you do it right, Return Value Optimization will allow the compiler to optimize out the redundant copy:To see that g++’s RVO will eliminate the copy, see http://ideone.com/loXAT