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

标签 c++ c++11

我需要创建一个大小为 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/

相关文章:

c++ - c++11 中的 <random> 库是可移植的吗?

c++ - 正确销毁指向对象的指针

c++ - 如何将 opengl 3.3 渲染成 SDL2 纹理?

c++ - 为什么要重新分配 vector 拷贝而不是 move 元素?

c++ - 提供方法指针和派生类型对象时 std::bind 的一致性

c++ - 随机数正态分布挂程序?

c++ - 在 C++ 中将像素阵列旋转 90 度

c++ - 在 C++ 中查看对象的未初始化属性

c++ - 在函数内部声明 char 数组时出现段错误

c++ - 将 std::unique_ptr 与标准容器一起使用