What if a C ++ class contains both a const reference constructor and a constructor without a constant reference?

fragment 1:

#include<iostream>
using namespace std;

class C{
public:
    C(){}
    C(const C& c){
        cout<<"const copy constructor called"<<endl;
    }
};
int main(){
    C c1;
    C c2 = c1;
    return 0;
}

conclusion : constructor const const called


fragment 2:

#include<iostream>
using namespace std;

class C{
public:
    C(){}
    C(const C& c){
        cout<<"const copy constructor called"<<endl;
    }
    C(C& c){
        cout<<"non-const copy constructor called.\t "<<endl;
    }
};
int main(){
    C c1;
    C c2 = c1;
    return 0;
}

conclusion : a non-content copy constructor called


fragment 3:

#include<iostream>
using namespace std;

class C{
public:
    C(){}
    C(const C& c){
        cout<<"const copy constructor called"<<endl;
    }
    C(C c){
        cout<<"non-const copy constructor called.\t "<<endl;
    }
};
int main(){
    C c1;
    C c2 = c1;
    return 0;
}

output : error: copy constructor must pass its first argument with a reference


I'm so confused:

  • for fragment 2, why is the non-content copy constructor valid here? why the constructor of a non-composite copy was called, and not a constant one.
  • for fragment 3, I know that the copy constructor should use a const reference to avoid infinite recursion. But here the class C has C(const C& c), C(C c)will not cause infinite recursion, why is it still not working?
+4
2

1: const T&. .

2:

, , - , T&, , const T&.

: T, T & const T & ( ), .

, Best Fit :

S1 , S2, :

  • ....
  • S1 S2 (8.5.3), , , , cv- , , , S2, cv-, , S1 .

,

C c1;
C c2 = c1;

, ,

,

const C c1;
C c2 = c1;

const const ( ), .

3 .

C(C c){
        cout<<"non-const copy constructor called.\t "<<endl;
    }

C(C c). , & , , . , .

@ , C(C& c) . const, , , .

+7

2, ? , .

, // (*):

int main(){
    const C c1; // (*) <- See change here
    C c2 = c1;
    return 0;
}

const copy ctor. , - , const, , const .

3, , const, . C C (const C & c), C (C c) , ?

, ( main ).

#include<iostream>
using namespace std;

class C{
public:
    C(){}
    C(const C& c){
        cout<<"const copy constructor called"<<endl;
    }
    C(C c){
        cout<<"non-const copy constructor called.\t "<<endl;
    }
};
int main(){
// Note that nothing is creating C instances at all.
return 0;
}

- , , .

" §12.8/3:

X , ( cv-) X , .

"

+3

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


All Articles