这是关于堆栈内存和堆内存交互的问题,特别是通过
原则上,
一个使用案例是,有一个返回
std::array
和 std::vector
类从堆栈到堆的情况。原则上,
std::array<T>
可以被视为指向第一个元素的指针,再加上一些编译时有关数组大小的信息。是否可能有一个 std::vector<T>
构造函数,考虑到这一点,并尝试通过复制指针来将 array
的内容移动到 vector
中。一个使用案例是,有一个返回
std::array<double, >
的函数:
std::array<double, 20> fun(){...};
但后来决定将其分配给一个 std::vector
,而不需要逐个复制元素。
std::vector<double> v = fun(); // 不起作用的代码
现在,必须执行以下操作:std::array<double, 20> tmp = fun();
std::vector<double> v(tmp.begin(), tmp.end());
如果这是可能的话,std::vector
的移动构造函数就不需要做一些冗余的工作了,例如:std::vector<double> v(std::move(tmp)); \\ 这段代码无法正常工作
。
std::vector
和 std::array
的内存布局相同,因此这不是障碍。
我理解主要障碍可能是std::array
元素位于堆栈中,而std::vector
元素位于堆中。显然,即使为std::vector
编写移动构造函数,来自堆栈的内存也将被不可撤销地销毁。
所以我猜这个问题也可以这样问:
是否有一种方法可以将内存从堆栈移动到堆中(无论这意味着什么),并且是否可以与移动构造函数结合使用?
或者说,std::vector
是否可以从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::vector
会像通常一样行事并重新分配(保留)更多内存(可能在内存的其他位置)。优化将丢失,但这不是问题的情况。 - alfCvector
类的非标准容器来说是有限制的。http://www.boost.org/doc/libs/1_60_0/doc/html/container/non_standard_containers.html#container.non_standard_containers.small_vector。据我所知,这仍然不包括不使用此优化的`std::vector`(但`std::basic_string`使用)。也许还有一种特定(虚假)分配器的`std::vector`的某种专门化,就像下面的评论之一。 - alfC