mercredi 28 janvier 2015

Is returning uniform initialized reference valid?

Is this code sample valid?



using ref = char&;

ref foo(ref x) {
return ref{x};
}

int main() {
char a;
foo(a);
return 0;
}


seems that:



  • clang 3.5 says YES


  • gcc 4.9 says NO



    main.cpp: In function 'char& foo(ref)':
    main.cpp:4:15: error: invalid cast of an rvalue expression of type 'char' to type 'ref {aka char&}'
    return ref{x};
    ^



http://ift.tt/1Db7x0v


So which compiler is right? or is it unspecified?


It very easy so overcome gcc build error by:




  1. using parenthesis instead of braces



    ref foo(ref x) {
    return ref(x);
    }



  2. by naming returned value



    ref foo(ref x) {
    ref ret{x};
    return ret;
    }



option 1. breaks uniform initialization, option 2. adds useless line of code.


Similar question was already aked here: Why can't I initialize a reference in an initializer list with uniform initialization?


But mentioned pr50025 is fixed in gcc 4.9.


I know that above code sample is pretty useless, but I did it intentionally to point out the issue. In real life code problem can be hidden in a generic function like:



#include <utility>
template <typename Tp, typename... Us>
Tp bar(Us&&... us) {
return Tp{std::forward<Us>(us)...};
}

Aucun commentaire:

Enregistrer un commentaire