c and c++ copy constructor and keyword explicit detail

  • 2020-06-07 05:01:31
  • OfStack

The keyword explicit

Modifies the constructor keyword to tell the compiler that an object cannot be implicitly initialized; You can implicitly initialize an object without adding;
The following code can be compiled and executed normally, but with the keyword explicit, the compilation will be wrong, because Test t = 100; This initializes the object implicitly, but if cast is added, there is no error.

Cast: Test t = (Test)100;

class Test{
 Test(int d):data(d){//explicit 
  cout << "C:" << this << endl;
int main(){
 Test t = 100;
 Copy constructor if added explicit , the following statement cannot be compiled through; No. 
class Test{
 // Copy constructor 
 explicit Test(const Test &t){
  data = t.data;
 int getData(){
  return data;
 int data;
void test(Test x){

int main(){
 Test t2(t1);// Call the copy constructor                     
 //Test t3 = t2;// Compile but  
 //test(t2);// Compile but  

Four ways to fire a copy constructor

The & # 8203; 1, Test t2 (t1); // Call the copy constructor

The & # 8203; 2. Assign Test t3 = t2 at the same time the declaration will call the copy constructor; Note, however, that this one does not call the copy constructor.

​ Test t3;

The & # 8203; t3 = t2; // will call the overloaded method of =

The & # 8203; 3, the parameter of the method is the object type test(t2);

The & # 8203; 4. The return value of the method is an object type. Reason: The object tmp is released after the end of the method, and to return out of the function, tmp must be copied.

But gdb looked at 1 under return did not call the copy constructor, so tmp is not released after the end of test method, the memory address of t5 calling test method is the same as tmp. Personal guess: The old VERSION of the gcc compiler might have called the copy constructor on return, but the new compiler (gcc 4.8.5-20) avoided one extra copy for efficiency.

void test(Test x){// The copy constructor is called when the function is entered 
 int value;
 value = x.getData();
 Test tmp(value);
 return tmp;//return The copy constructor is called at the time of 
Test t5 = test(t1);

Related articles: