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 returns a std::array<double, >
std::array<double, 20> fun(){...};
but one later decides to assign it to a std::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 could be 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 question can also be read as:
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 if std::vector can 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
}
std::vectorwill behave as it usually does and reallocate (reserve) more memory (possible somewhere else in memory). The optimization will be lost but that is not the case of the question.vectorclasses using the "small vector optimization". boost.org/doc/libs/1_60_0/doc/html/container/… . AFAIK that still excludesstd::vectorwhich doesn't use this optimzation (butstd::basic_stringdoes). Maybe also a certain specialization ofstd::vectorwith a particular (fake) allocator like in one of the comments below.