gpt4 book ai didi

c++ - std::move 对堆栈变量有意义吗

转载 作者:行者123 更新时间:2023-12-03 10:05:19 25 4
gpt4 key购买 nike

我需要创建一个大小为 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;
};
然后,它会有所作为—— vector 数据成员将被移动而不是被复制。
简而言之,我的建议是关注移动操作的语义——即,移动对象是否有意义?好吧,如果您无论如何都要处理该对象,那么它很可能会处理。

关于c++ - std::move 对堆栈变量有意义吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65457181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com