KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
The following code only works when the copy constructor is available. When I add print statements (via std::cout ) and make the copy constructor available it is not used (I assume there is so compiler trick happening to remove the unnecessary copy). But in both the output operator << and the function plop() below (where I create a temporary object) I don't see the need for the copy constructor. Can somebody explain why the language needs it when I am passing everything by const reference (or what I am doing wrong). #include <iostream> class N { public: N(int) {} private: N(N const&); }; std::ostream& operator<<(std::ostream& str,N const& data) { return str << "N\n"; } void plop(std::ostream& str,N const& data) { str << "N\n"; } int main() { std::cout << N(1); // Needs copy constructor (line 25) plop(std::cout,N(1)); // Needs copy constructor N a(5); std::cout << a; plop(std::cout,a); } Compiler: [Alpha:~/X] myork% g++ -v Using built-in specs. Target: i686-apple-darwin10 Configured with: /var/tmp/gcc/gcc-5646~6/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple-darwin10 Thread model: posix gcc version 4.2.1 (Apple Inc. build 5646) [Alpha:~/X] myork% g++ t.cpp t.cpp: In function ‘int main()’: t.cpp:10: error: ‘N::N(const N&)’ is private t.cpp:25: error: within this context t.cpp:10: error: ‘N::N(const N&)’ is private t.cpp:26: error: within this con
Tags (comma-separated)
Save Edits
Cancel