samedi 11 mars 2017

Using temporary object by non-const reference within a single statement in C++

Here is the code:

namespace NS
{
    class B
    {
    public:
        template<typename T> friend B& operator<<(B& b, T const& obj);
    };

    template<typename T> B& operator<<(B& b, T const& obj)
    {
        // using b and obj
        return b;
    }
}

int main()
{
    NS::B() << 2.71 << 123 << "abcdef"; // doesn't compile in gcc
    NS::B b; b << 2.71 << 123 << "abcdef"; // OK
}

The first line in main compiles in VS2015 (and some earlier ones) and doesn't compile in gcc (I tried in 6.3, 4.3.2).

Which compiler does the right thing? I thought the temporary object's (NS::B()) lifetime would be up to the end of the statement (;), so it's ok to pass it to my operator<< by non-const reference. If it isn't so, could you tell me why?

Thanks.

Aucun commentaire:

Enregistrer un commentaire