Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copying C-style arrays and structure

C++ does not allow copying of C-style arrays using =. But allows copying of structures using =, as in this link -> Copying array in C v/s copying structure in C.It does not have any credible answers yet. But consider following code

#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;
}

Above code segment didn't gave any kind of errors and warnings, and just works fine. WHY? Consider explaining both questions(this one and the one linked above).

like image 852
beta_me me_beta Avatar asked Dec 07 '22 10:12

beta_me me_beta


2 Answers

Your class user gets an implicitly declared copy constructor and implicitly declared copy assignment operator.

The implicitly declared copy assignment operator copies the content from b to a.

Two passages from the standard that seems to apply:

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;

like image 113
Ted Lyngmo Avatar answered Dec 30 '22 00:12

Ted Lyngmo


Yes, the code should work fine. arrays can't be assigned directly as a whole; but they can be assigned as data member by the implicity-defined copy assignment operator, for non-union class type it performs member-wise copy assignment of the non-static data member, including the array member and its elements.

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
like image 34
songyuanyao Avatar answered Dec 30 '22 01:12

songyuanyao