代码之家  ›  专栏  ›  技术社区  ›  Harry

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

  •  3
  • Harry  · 技术社区  · 4 年前

    我需要创建一个1024大小的结构列表。所以我试图通过使用move语义优化push操作到列表中。但是移动语义只对堆分配的内存有意义(据我所知)。有人能给我一个更好的方法吗。这是我的密码

    #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;
    }
    
    2 回复  |  直到 4 年前
        1
  •  4
  •   jfMR    4 年前

    根据你现在对 St :

    struct St {
        int32_t arr[1024];
    };
    

    St

    然而,从语义上来说,标记是有意义的 st 因为你已经走了,而且 st St

    struct St {
        std::vector<int32_t> vec;
    };
    

    简而言之,我的建议是 语义学 移动物体有意义吗? 好吧,如果你无论如何都要处理这个对象,那么它很可能会。

        2
  •  1
  •   JVApen    4 年前

    the return value of emplace_back 以便先将其添加到列表中,然后再进行填充。 您可以(如果默认可构造,例如您的示例)首先将_放置回一个新实例,然后使用 .back() 把它填进去。

    堆栈分配和释放并不昂贵,尤其是对于pod。重要的是你对它的逻辑。

    std::string ,std::move将允许您将字符串从一个数组移动到另一个数组。