Hey folks,
just found out that stream operators are treated in a different way when using GCC or Clang as compilers. Until now, I always assumed that something like this was the way to go when moving objects to a stream:
Code:
std::vector<int> values{1, 2, 3};
// stream the number of elements, then move the object
stream << values.size() << std::move(values);
Somehow however the value returned by `values.size()' isn't the same when using different compilers: with GCC the stream object will receive the value `0', whereas with Clang it gets (the correct) value `3'.
I'm not really sure which one does it the right way, or if there is a right way at all. Below is some code I used for testing:
Code:
class test {
public:
test& operator<<(std::vector<int> values);
test& operator<<(std::size_t count);
void view();
private:
std::vector<int> m_values;
std::size_t m_count{0};
};
test& test::operator<<(std::vector<int> values)
{
m_values=std::move(values);
return *this;
}
test& test::operator<<(std::size_t count)
{
m_count=count;
return *this;
}
void test::view()
{
std::cout << "test instance" << std::endl;
std::cout << " values: ";
for (const auto& value:m_values) {
std::cout << "<" << value << "> ";
}
std::cout << std::endl << " count: " << m_count << std::endl;
}
int main()
{
{ // first test
std::vector<int> values{1, 2, 3};
test object;
object << std::move(values) << values.size();
object.view();
}
{ // second test
std::vector<int> values{1, 2, 3};
test object;
object << values.size() << std::move(values);
object.view();
}
}
Code:
[milli-961227@milli-notebook]$ g++ -std=c++1y stream.cc
[milli-961227@milli-notebook]$ ./a.out
test instance
values: <1> <2> <3>
count: 3
test instance
values: <1> <2> <3>
count: 0
[milli-961227@milli-notebook]$ clang++ -std=c++1y stream.cc
[milli-961227@milli-notebook]$ ./a.out
test instance
values: <1> <2> <3>
count: 0
test instance
values: <1> <2> <3>
count: 3