在哪种情况下是C ++复制构造函数调用? [英] In which situations is the C++ copy constructor called?

查看:200
本文介绍了在哪种情况下是C ++复制构造函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在c ++中将调用复制构造函数的以下情况:


  1. 它自己类的对象

      MyClass A,B; 
    A = new MyClass();
    B = A; //复制构造函数称为


  2. 如果函数接收到作为参数传递的值,的类

      void foo(MyClass a); 
    foo(a); //复制构造函数调用


  3.   MyClass foo()
    {
    MyClass temp;
    ....
    return temp; // copy constructor called
    }


请随时更正我所做的任何错误;但我更好奇,如果有任何其他情况下,其中复制构造函数被调用。

解决方案

,但是这个类允许你看到什么叫什么时候:

  class a {
public:
a(){
printf(constructor called\\\
);
};
a(const a& other){
printf(copy constructor called\\\
);
};
a& operator =(const a& other){
printf(copy assignment operator called\\\
);
return * this;
};
};

那么这段代码:

  ab; // constructor 
a c; // constructor
b = c; // copy assignment
c = a(b); //复制构造函数,然后复制赋值

产生结果:



构造函数
构造函数称为
复制赋值运算符
复制构造函数称为
复制赋值运算符

另一个有趣的事情,说你有以下代码:

  a * b = new a(); // constructor called 
a * c; //什么都不叫
c = b; //仍然没有调用
c = new a(* b); //复制构造函数被调用

这是因为当你分配一个指针时,实际对象。


I know of the following situations in c++ where the copy constructor would be invoked:

  1. when an existing object is assigned an object of it own class

    MyClass A,B;
    A = new MyClass();
    B=A; //copy constructor called 
    

  2. if a functions receives as argument, passed by value, an object of a class

    void foo(MyClass a);
    foo(a); //copy constructor invoked
    

  3. when a function returns (by value) an object of the class

    MyClass foo ()
       {
          MyClass temp;
          ....
          return temp; //copy constructor called
       } 
    

Please feel free to correct any mistakes I've made; but I am more curious if there are any other situations in which the copy constructor is called.

解决方案

I might be wrong about this, but this class allows you to see what is called and when:

class a {
public:
    a() {
        printf("constructor called\n");
    };  
    a(const a& other) { 
        printf("copy constructor called\n");
    };    
    a& operator=(const a& other) {
        printf("copy assignment operator called\n");
        return *this; 
    };
};

So then this code:

a b; //constructor
a c; //constructor
b = c; //copy assignment
c = a(b); //copy constructor, then copy assignment

produces this as the result:

constructor called
constructor called
copy assignment operator called
copy constructor called
copy assignment operator called

Another interesting thing, say you have the following code:

a* b = new a(); //constructor called
a* c; //nothing is called
c = b; //still nothing is called
c = new a(*b); //copy constructor is called

This occurs because when you when you assign a pointer, that does nothing to the actual object.

这篇关于在哪种情况下是C ++复制构造函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆