复制 C 风格的数组和结构

copying C-style arrays and structure

C++ 不允许使用 = 复制 C 风格数组。但允许使用 = 复制结构,如 link -> Copying array in C v/s copying structure in C。它还没有任何可靠的答案。 但是请考虑以下代码

#include <iostream>
using namespace std;

struct user {
    int a[4];
    char c;
};

int main() {
    user a{{1,2,3,4}, 'a'}, b{{4,5,6,7}, 'b'};
    a = b;             //should have given any error or warning but nothing
    return 0;
}

以上代码段没有给出任何类型的错误和警告,并且工作正常。为什么? 考虑解释这两个问题(这个问题和上面的 linked)。

您的 class user 获得 implicitly declared copy constructor and implicitly declared copy assignment operator

隐式声明的复制赋值运算符将内容从b复制到a

似乎适用的标准中的两段话:

class.copy.ctor

if the member is an array, each element is direct-initialized with the corresponding subobject of x;

class.copy.assign

if the subobject is an array, each element is assigned, in the manner appropriate to the element type;

是的,代码应该可以正常工作。 arrays can't be assigned directly as a whole; but they can be assigned as data member by the implicity-defined copy assignment operator,对于非联合 class 类型,它执行非静态数据成员的成员方式复制分配,包括数组成员及其元素。

Objects of array type cannot be modified as a whole: even though they are lvalues (e.g. an address of array can be taken), they cannot appear on the left hand side of an assignment operator:

int a[3] = {1, 2, 3}, b[3] = {4, 5, 6};
int (*p)[3] = &a; // okay: address of a can be taken
a = b;            // error: a is an array
struct { int c[3]; } s1, s2 = {3, 4, 5};
s1 = s2; // okay: implicity-defined copy assignment operator
         // can assign data members of array type