How are C++ array members handled in copy control functions?

前端 未结 2 1829
情书的邮戳
情书的邮戳 2020-11-27 15:59

This is something I have wondered for a long time. Take the following example:

struct matrix
{
    float data[16];
};

I know what the defau

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 16:40

    Both copies elements in the array (instead of doing nothing or copying pointer).

    struct X
    {
        char data_[100];
    };
    
    
    int main () 
    {
        X orig, copy_assign;
        orig.data_[10] = 'a';
        copy_assign = orig;
        X copy_constructor(orig);
        printf("orginal10:%c, copy_assign10:%c, copy_constructor10:%c\n",orig.data_[10],copy_assign.data_[10],copy_constructor.data_[10]);
        copy_assign.data_[10] = 'b';
        printf("original10:%c, copy_assign10:%c, copy_constructor10:%c\n",orig.data_[10],copy_assign.data_[10],copy_constructor.data_[10]);
        copy_constructor.data_[10] = 'c';
        printf("original10:%c, copy_assign10:%c, copy_constructor10:%c\n",orig.data_[10],copy_assign.data_[10],copy_constructor.data_[10]);
        return 0;
    }
    

    running results:

    orginal10:a, copy_assign10:a, copy_constructor10:a
    original10:a, copy_assign10:b, copy_constructor10:a
    original10:a, copy_assign10:b, copy_constructor10:c
    
    • From the first line of the result, we can see that at least something was copied (it is either the elements in the array, or the array pointer was copied).
    • From the next two lines, we can see that changing copy assigned objects and copy constructed objects' array did not change the original array. Therefore we conclude that elements were copied instead of array pointer.

    Hope this example is clear.

提交回复
热议问题