Emil Kirichev
Emil Kirichev

Reputation: 189

A gcc compilation error (concerning copy c'tors) which seems odd (at least to me)

So, I have the following code which fails to compile on gcc 4.2.1 on OSX. The error I get 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's 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, as f gets a reference (I made it public to see if it gets called and it doesn't). Additionally, I've made f get the object by value, and still neither copy constructor nor operator= gets called. I suspect this may have something to do with optimizations. Any suggestions? Thanks.

Upvotes: 4

Views: 329

Answers (1)

Adam Wright
Adam Wright

Reputation: 49386

You've fallen into a subtle standards issue. GCC is right, but the error is pretty bad: Compiling the same 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 don't have my standards copy nearby to give you the full reasoning. Hopefully someone else (or Google) can.

Upvotes: 2

Related Questions