这是一个关于堆栈内存和堆内存的交互以及通过std::array
和std::vector
类从堆栈到堆的特殊情况的问题。
原则std::array<T>
上可以看作是指向第一个元素的指针,加上一些关于数组大小的编译时信息。是否有可能让std::vector<T>
构造函数考虑到这一事实并尝试通过复制指针将 的内容移动array
到just 中。vector
一个用例是,一个函数返回一个std::array<double, >
std::array<double, 20> fun(){...};
但后来决定将其分配给 astd::vector
而无需逐个元素复制。
std::vector<double> v = fun(); // not working code
现在必须做
std::array<double, 20> tmp = fun();
std::vector<double> v(tmp.begin(), tmp.end());
这实际上做了一些多余的工作,如果可能的话,这些工作就没有必要了std::vector<double> v(std::move(tmp)); \\ not working code
。
std::vector
和的内存布局std::array
是一样的,所以不是和障碍。
我知道主要障碍可能是std::array
元素在堆栈中,而std::vector
元素在堆中。很明显,即使编写移动构造函数,std::vector
堆栈中的内存仍将被不可撤销地破坏。
所以我想这个问题也可以理解为:
有没有办法将内存从堆栈移动到堆(无论这意味着什么),如果它可以与移动构造函数结合使用?
或者,如果原则上std::vector
可以有一个来自 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
}