lundi 27 mai 2019

Why the declaration with equal operator is Error when I declare copy initializer is deleted

the class A is declare as follow:

class A {
public:
    A() {
        cout<<"A()"<<'\n';
    }
    A(int i) {
        cout<<"A(int i)"<<'\n';
    }
    A(const A& a_) {
        cout<<"A(const A& a_)"<<'\n';
    }
};

when I initialize 'A' by an integer with equal operator:

int main() {
    A a = 123;
    return 0
}

then it only output: "A(int i)" so I guess it only invoke A::A(int i) and the copy constructor is never used in this situation.

But when I declare "A::A(const A& a_) = delete",the codes as follow:

class A {
public:
    A() {
        cout<<"A()"<<'\n';
    }
    A(int i) {
        cout<<"A(int i)"<<'\n';
    }
    A(const A& a_) = delete;
};
int main() {
    A a = 123;
    return 0;
}

the compiler issues an error: "Copying variable of type 'A' invokes deleted constructor".

so my question is why the copy constructor can't be deleted even it's not invoked in this situation

Aucun commentaire:

Enregistrer un commentaire