Boost logo

Boost :

Subject: [boost] proposal a movable_initializer_list
From: 何子杰Hzj_jie (hzj_jie_at_[hidden])
Date: 2014-09-15 03:39:09


hi, all,

the initializer_list in c++11 does not support the inner objects to be moved, so in some scenarios the performance will be significant impacted. say, an event class, which stores several std::function objects, and execute them later. the prototype is

template <typename Args…>

class event

{

private:

    std::vector<std::function<void(Args…)>> v;

public:

    event(std::initializer_list<std::function<void(Args…)>>);

    void bind(std::function<void(Args…)>&&);
};

When calling the constructor of event with a set of lambda expressions, the std::function objects will be copied instead of moved, and cause performance impact. Though pointer can resolve the issue, the syntax is not friendly, and the user needs to delete the instances manually.

So I proposal a movable_initializer_list, it accepts two ways to construct, with an initializer_list<T*> or initializer_list<T>, the prototype is,

template <typename T>

class movable_initializer_list

{

private:

    std::vector<T> v;

public:

    movable_initializer_list(std::initializer_list<T*>);

    movable_initializer_list(std::initializer_list<T>);

// other functions same as initializer_list
};


The implementation of T* overloads is something like

movable_initializer_list<std::initializer_list<T*> x)

{

    for(auto it : x)

    {

        assert((*it) != nullptr);

        v.push_back(std::move(**it));

        delete *it;

    }
}

While the implementation of T overloads is something like

moveable_initializer_list<std::initializer_list<T> x)
{

    for(auto it : x) v.push_back(move(*it));
}


Surely end-users need to aware the implementation of movable_initializer_list will move the objects instead of copy.


The full implementation is at https://github.com/Hzj-jie/osi/blob/master/formation/movable_initializer_list.hpp, and the test is at https://github.com/Hzj-jie/osi/blob/master/utt_cases/formation/movable_initializer_list_test.hpp.


Please feel free to give me some suggestions about this proposal.


Thank you in advanced.




.Hzj_jie


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk