C ++ error when using stream buffers directly with ?: Operator

When I try to use the ternary conditional operator (? :) with the flow buffer redirection, gcc produces the "synthesized method first required here". What is the problem and how to fix the following program?

#include <fstream>
#include <iostream>

int main(int argc, char* argv[])
{
    using namespace std;
    cout << cin.rdbuf();    //OK
    ofstream("tmp.txt") << cin.rdbuf(); //OK

    int i=1;
    (i > 1 ? ofstream("tmp.txt") : cout) << cin.rdbuf(); //Compilation ERROR. Why?
    return 0;
}

compiled with gcc4.4:

...    
/usr/include/c++/4.4/bits/ios_base.h: In copy constructor β€˜std::basic_ios<char,   std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)’:  
/usr/include/c++/4.4/bits/ios_base.h:790: error: β€˜std::ios_base::ios_base(const std::ios_base&)’ is private  
/usr/include/c++/4.4/iosfwd:47: error: within this context  
/usr/include/c++/4.4/iosfwd: In copy constructor β€˜std::basic_ostream<char,   std::char_traits<char> >::basic_ostream(const std::basic_ostream<char,   std::char_traits<char> >&)’:  
/usr/include/c++/4.4/iosfwd:56: note: **synthesized method** β€˜std::basic_ios<char,   std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)’   **first required here**   
../item1_1.cpp: In function β€˜int main(int, char**)’:  
../item1_1.cpp:12: note: synthesized method β€˜std::basic_ostream<char,   std::char_traits<char> >::basic_ostream(const std::basic_ostream<char,   std::char_traits<char> >&)’ first required here   
+3
source share
3 answers

This compiled with my version of clang, I think it could be a gcc bug.

From my reading of the standard, coutis an lvalue type std::ostreamand ofstream("tmp.txt")is an rvalue type std::ofstream.

cv- std::ostream std::ofstream, , r- std::ostream.

.

E1 E2 , : E1 E2, T2 , T1, cv- T2 cv-, cv-, cv- T1. , E1 rvalue T2, ( ). [: . ]

operator<<, , std::ostream, , r. >

basic_ostream<charT,traits>&
    basic_ostream<charT,traits>::operator<< (basic_streambuf<charT,traits>* sb);

Edit

, ++ 0x. , rvalue, . ostream , ++ 0x.

: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#446

+5

:

#include <fstream>
#include <iostream>

int main(int argc, char* argv[])
{
    using namespace std;
    ofstream file("tmp.txt");
    int i=1;
    (i > 1 ? file : cout) << cin.rdbuf();
    return 0;
}

gcc 4.4.3.

, , .

. , , .

+1

:

  • cout ostream, () , .
  • even if they are convertible, the result is a temporary rvalue and does not bind to the <<operator since this requires a non-contact link.
0
source

Source: https://habr.com/ru/post/1794933/


All Articles