can memcpy() be used to change “const” member data?

前端 未结 2 1183
感情败类
感情败类 2021-01-13 11:44

For a struct with const members

struct point { const int x; const int y; };

that is used as member data



        
2条回答
  •  半阙折子戏
    2021-01-13 12:18

    You will get a compiler error trying to use memcpy with a const member as follows:

    #include 
    #include 
    #include 
    
    struct foo
    {
        public:
            foo(int init_x);
            const int x;
            int bar();
    };
    
    foo::foo(int init_x): x(init_x) {}
    
    int foo::bar()
    {
        int *y = (int *) malloc(sizeof(int));
        *y = 6;
        memcpy(&x, y, sizeof(int));
        return x;
    }
    
    int main(int argc, char *argv[])
    {
        foo f{5};
        printf("%d\n", f.bar());
    }
    

    The above results in

    error: invalid conversion from ‘const void*’ to ‘void*’ [-fpermissive]
        memcpy(&x, y, sizeof(int));
    

    While I used const int in this example, you will find the same result if you instead use a const int pointer member, i.e.

    const int *x;
    

    But, if you remove the const descriptor and use:

    int x;
    

    (or int *x;, for that matter) the error no longer happens, and the program prints 6, as one might expect.

    So this begs the question, if you know something is going to be declared as const:

    • If you have the ability to change the declaration, couldn't you remove const yourself?
    • If you can't change the declaration, is there a good reason you're looking to break the "promise" that const makes?

提交回复
热议问题