In which situations is the C++ copy constructor called?

后端 未结 7 1712
梦毁少年i
梦毁少年i 2020-12-23 02:06

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

7条回答
  •  难免孤独
    2020-12-23 02:41

    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.

提交回复
热议问题