c++ - Why is vector::push_back of local variable not move optimized? -
this question has answer here:
in c++11 can use std::vector::push_back in combination std::move avoid copies while inserting elements vector. there section in standard forbids compilers use std::move automatically local variables not used after calls push_back? when filling vectors large elements, huge performance benefit.
i checked following code gcc 7.1.0 , -o3 , version 1 prints move while version 2 prints copy.
#include <iostream> #include <string> #include <vector> struct s { s() = default; s(s const&) { std::cout << "copy" << std::endl; } s(s &&) { std::cout << "move" << std::endl; } std::string a; std::string b; }; void fill_members(s& s) { /*...*/ } int main() { std::vector<s> v; { s s; // somehow fill members of s, maybe use function call that. fill_members(s); // version 1: // avoids copy, since there explicit std::move. v.push_back(std::move(s)); // version 2: // why dont compilers optimize std::move? // compiler can see s not used after line. v.push_back(s); } }
Comments
Post a Comment