lundi 20 juillet 2020

Custom stream class used as temporary

I want to code another stream class. Done it before like this:

class MyStream
{
   // ...
};

template <typename T>
MyStream& operator <<(MyStream& s, const T& t) noexcept
{
   std::cout << t;
   return s;
}

void f()
{
   MyStream s;
   s << 666;
}

This time I need to make it work with temporaries as well:

void f()
{
   MyStream() << 666;

   MyStream s;
   s << 777;
}

I understood that this can be solved using an rvalue reference:

template <typename T>
MyStream& operator <<(MyStream&& s, const T& t) noexcept
{
   std::cout << t;
   return s;
}

However I do not understand the implications of doing so.

Should I implement a conventional lvalue reference operator as well? Is there anything that could go wrong? Is it ok to convert a rvalue reference into a lvalue reference like this?

Aucun commentaire:

Enregistrer un commentaire