我需要创建一个大小为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;
};
然后,这将有所作为–向量数据成员将被移动而不是被复制。
简而言之,我的建议是集中于移动操作的语义-即,移动对象是否有意义?好吧,如果您仍然要处理该对象,那么很有可能会这样做。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句