A gcc compilation error (regarding c'tors copies) that seems odd (at least to me)

So, I have the following code that cannot be compiled on gcc 4.2.1 on OSX. The error I am getting is:

testref.cpp: In function 'int main()': testref.cpp:10: error: 'A::A(const A&)' is private testref.cpp:20: error: within this context 

And here is the code

 #include <cstdio> class A { public: A() { i=0; printf("A ctor\n"); } ~A() { printf("A dtor\n"); } private: A(const A& other) { i=other.i; printf("A COPY CTOR\n"); } A& operator=(const A& other) { i=other.i; printf("A COPY operator\n"); return *this; } private: int i; }; void f(const A &aref) { printf("dummy\n"); } int main() { f(A()); return 0; } 

This copy constructor is not needed in this case, since f gets the link (I made it public to find out if it was called, and it was not specified). In addition, I made f the value of the object by value, and so far no copy constructor or operator = has been called. I suspect this may be due to optimization. Any suggestions? Thanks.

+4
source share
1 answer

You have fallen into the subtle problem of standards. GCC is right, but the error is pretty bad: compiling with clang gives:

 test.cpp:20:7: warning: C++98 requires an accessible copy constructor for class 'A' when binding a reference to a temporary; was private 

Edit: I do not have my copy of the standards nearby to give you full reasoning. Hope someone else (or Google) can.

+2
source

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


All Articles