高效优雅的初始化矢量方式

dat*_*ats 6 c++ move initializer-list c++14

给出以下C++ 14代码:

struct A { /* heavy class, copyable and movable */ };

// complex code to create an A
A f(int);
A g(int);
A h(int);

const std::vector<A> v = { f(1), g(2), h(3) };
Run Code Online (Sandbox Code Playgroud)

我知道Ainitializer_list中的's被复制到向量中,而不是被移动(stackoverflow中有很多关于此的问题).

我的问题是:如何它们移动到矢量中?

我只能做丑陋的IIFE(保持vconst)并且只是避免了initializer_list:

const std::vector<A> v = []()
{
    std::vector<A> tmp;
    tmp.reserve(3);
    tmp.push_back( f(1) );
    tmp.push_back( g(2) );
    tmp.push_back( h(3) );
    return tmp;
}();
Run Code Online (Sandbox Code Playgroud)

是否有可能使这优雅高效?

PD:v 必须std::vector<A>以后使用

Chr*_*rew 7

不确定它是否算作"优雅"但你可以使用一个数组(或std::array),它使用不受此问题影响的聚合初始化move_iterator并将值移动到vector.

std::array<A, 3> init = { f(1), g(2), h(3) };

std::vector<A> v{std::make_move_iterator(init.begin()), 
                 std::make_move_iterator(init.end())};
Run Code Online (Sandbox Code Playgroud)

现场演示.