为什么局部变量的vector :: push_back没有移动优化?

psc*_*ill 5 c++ stdvector compiler-optimization move-semantics c++11

在C++ 11中,您可以std::vector::push_back结合使用,std::move以便在将元素插入向量时避免复制.标准中是否有一节禁止编译器std::move自动使用调用后未使用的局部变量push_back?当填充具有大元素的向量时,这可以是巨大的性能益处.

我使用gcc 7.1.0检查了以下代码,并且在版本2打印时打印-O3了版本1 .movecopy

#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 a function call for that.
        fill_members(s);

        // Version 1:
        // This avoids a copy, since there is an explicit std::move.
        v.push_back(std::move(s));

        // Version 2:
        // Why dont compilers optimize this with std::move?
        // The compiler can see that s is not used after this line.
        v.push_back(s);
    }
}
Run Code Online (Sandbox Code Playgroud)