vendredi 31 mars 2017

Why C++ std::move does not work on std::initializer_list ? Rvalue

In the funtions bellow, doA is overrided to accept const& and && of std::string, doA_ is overrided to accept these two types of std::initializer_list. But what seems to be wrong is that, in the fisrt doA_ function, a std::move does not correctly cast 'std::string' to 'std::string&&', so there the second doA called,not the first one. Even if I use 'doA(static_case(*it))' instead,it is the same result.However , if I use 'doA("a string")',then the first doA called. Why is that?Why do they behave differently?

#include <string>
#include <iostream>

void doA(std::string &&s)
{
        std::cout << "doA && "<<std::endl;
}

void doA(const std::string &s)
{
        std::cout << "doA const & "<<std::endl;
}
void doA_(initializer_list<std::string> &&l)
{
        std::cout << "doA_ &&"<<std::endl;
        auto it=std::begin(l);
        doA(std::move(*it));//print 'doA const &',but it is expected to be 'doA &&'
        //doA(static_cast<const std::string &&>(*it));  //same with above
        //doA("a string");   //print 'doA &&'
              //======Doesn't work as expected

}
void doA_(const initializer_list<std::string> &l)
{
        std::cout << "doA_ const &"<<std::endl;
        auto it=std::begin(l);
        doA(*it);
}


int main()
{
        initializer_list<std::string> l={"a","b"};
        doA_(l);//doA_ const &
        doA_(std::move(l));//doA_ &&
        doA_({"c","d"});//doA_ &&
        return 0;
}

//=========output
    doA_ const &
    doA const &
    doA_ &&
    doA const &
    doA_ &&
    doA const &

Aucun commentaire:

Enregistrer un commentaire