Jul 10, 2019

[c++] initializer_list as r-value provides looping source

Nicolai Josuttis shared a trick about using std::ref + std::initializer_list:
https://twitter.com/NicoJosuttis/status/1148659818770640896

Back in the old days @VMW we have vmw::ref as reference counter type for our objects, here, std::ref is a free function returns std::reference_wrapper which ref-init the passing in object.

Since C++14, the underline implement of std::initializer_list has been standardized, states that:
The underlying array is a temporary array of type const T[N], in which each element is copy-initialized.

Modified sample code address this in more detailed phase:
#include <iostream>
#include <functional>

using namespace std;

struct Fun{
    int data = 42;
    Fun() = default;
    Fun(const Fun&) = delete;
};


int main(){
    Fun f1;
    Fun f2;
    for(auto& a : {ref(f1), ref(f2)}){
        cout << a.get().data << endl;
    }

    for(auto& a : {Fun{}, Fun{}}){
        cout << a.data << endl;
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.