mardi 1 décembre 2015

Is it possible to move an std::array into a std::vector?

This is a question about the interaction of stack memory and heap memory and the particular case of going from stack to heap via the std::array and std::vector classes.

In principle std::array<T> can be seen as a pointer to the first elements, plus some compile time information about the size of the array. Would it be possible to have std::vector<T> constructor that takes into account that fact and tries to move contents of the array into the vector just by copying the pointer.

A use case would be, that one has a function that return a std::array<double, >

std::array<double, 20> fun(){...};

but one later decides t assign it to a vector without the necessity of copying element by element.

std::vector<double> v = fun(); // not working code

Right now one has to do

std::array<double, 20> tmp = fun();
std::vector<double> v(tmp.begin(), tmp.end());

Which actually does some redundant work which wouldn't be necessary if this were possible std::vector<double> v(std::move(tmp)); \\ not working code.

The memory layout of std::vector and std::array is the same so that is not and obstacle.

I understand that the main obstacle is that std::array elements are in the stack while std::vector elements are in the heap. It is clear that even if one writes the move constructor for std::vector still the memory from the stack will be irrevocably destructed.

So I guess that this is question is really if

Is there a way to move memory from the stack to the heap (whatever that means) and if that can be combined with a move constructor?

Or can std::vector have in principle a move constructor from a std::array?

MWE:

#include<array>
#include<vector>

std::array<double, 20> fun(){return {};} // don't change this function

int main(){
    std::array<double, 20> arr = fun(); // ok
    std::vector<double> v(arr.begin(), arr.end()); // ok, but copies and the allocation is duplicated
    std::vector<double> v2 = fun(); // not working, but the idea is that the work is not duplicated
}

Aucun commentaire:

Enregistrer un commentaire