How to use const_cast?

南笙酒味 提交于 2019-12-17 07:05:42

问题


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

const int studentNumnber;

I am trying to write a copy constructor for the Student and I need to cast away the constness to do this, unfortunately I don't understand how to use std::const_cast.

This is what I am trying to do in my copy constructor:

    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*>(this)->studentNumber = s.studentNumber;
        //studentNumber = s.studentNumber);
    }

This doesn't work... I am unsure of what the syntax is to do this.


回答1:


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)
{
    // ...
}



回答2:


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


来源:https://stackoverflow.com/questions/19554841/how-to-use-const-cast

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!