How to use const_cast?

前端 未结 2 1755
遇见更好的自我
遇见更好的自我 2020-11-27 11:37

I have a private variable in my Student class defined as:

const int studentNumnber;

I am trying to write a copy constructor fo

相关标签:
2条回答
  • 2020-11-27 11:58

    In your code you are trying cast this pointer instead of variable. You can try the following:

    Student(const Student & s)
        : Person(p.getName(), p.getEmailAddress(), p.getBirthDate()), school(0), studentNumber(0) {
        school = new char[strlen(s.school) + 1];
        strcpy_s(school, strlen(s.school) + 1, s.school);
        *const_cast<int*>(&studentNumber) = s.studentNumber;
    }
    
    0 讨论(0)
  • 2020-11-27 12:07

    You are not allowed to const_cast variables that are actually const. This results in undefined behavior. const_cast is used to remove the const-ness from references and pointers that ultimately refer to something that is not const.

    So, this is allowed:

    int i = 0;
    const int& ref = i;
    const int* ptr = &i;
    
    const_cast<int&>(ref) = 3;
    *const_cast<int*>(ptr) = 3;
    

    It's allowed because i, the object being assigned to, is not const. The below is not allowed:

    const int i = 0;
    const int& ref = i;
    const int* ptr = &i;
    
    const_cast<int&>(ref) = 3;
    *const_cast<int*>(ptr) = 3;
    

    because here i is const and you are modifying it by assigning it a new value. The code will compile, but its behavior is undefined (which can mean anything from "it works just fine" to "the program will crash".)

    You should initialize constant data members in the constructor's initializers instead of assigning them in the body of constructors:

    Student(const Student & s) 
        : Person(p.getName(), p.getEmailAddress(), p.getBirthDate()),
          school(0),
          studentNumber(s.studentNumber)
    {
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题