问题描述
我需要创建一个大小为 1024 的结构列表。所以我试图通过使用移动语义来优化对列表的推送操作。但是移动语义仅对堆分配的内存有意义(据我所知)。有人可以建议我这样做的更好方法。这是我的代码
#include <iostream>
#include <list>
struct St {
int32_t arr[1024];
};
int main() {
std::list<St> struct_list;
for(int32_t i = 0; i < 1024; ++i) {
St st; // stack allocated and memory gets deallocated after each loop
std::cout << &st << std::endl;
struct_list.emplace_back(std::move(st)); // I feel std::move doesn't make any sense here even if I implement move constructor,still data gets copied into the std::list which is allocated in heap,so not efficient.
std::cout << &struct_list.back() << "\n" << std::endl;
}
return EXIT_SUCCESS;
}
解决方法
鉴于您当前对 St
的定义:
struct St {
int32_t arr[1024];
};
从技术上讲,对于 St
的这个特定定义,移动和复制两个结果是相同的。
但是,从语义上讲,在完成移动后将 st
标记为移动是有意义的,而 st
无论如何都会被销毁。例如,如果您后来决定将 St
的定义更改为:
struct St {
std::vector<int32_t> vec;
};
然后,它会有所作为——向量数据成员将被移动而不是被复制。
简而言之,我的建议是关注移动操作的语义——即,移动对象是否有意义?好吧,如果你无论如何都会处理该对象,那么它很可能会处理。
,如果您想升级到 C++17,您可以使用 the return value of emplace_back 来先将它添加到列表中,然后再填充它。
您可以(如果默认可构造,如您的示例)首先 emplace_back 一个新实例,然后使用 .back()
获取它并填充它。
堆栈分配和解除分配并不昂贵,尤其是对于 POD。重要的是你对它所做的逻辑。
关于移动,在这个例子中,std::move 的作用与复制相同,所以不,你不需要它。但是,如果这是一个 std::string
数组,则 std::move 将允许您将字符串从一个数组移动到另一个数组。