【问题标题】:How to use const_cast?如何使用 const_cast?
【发布时间】:2013-11-02 12:08:17
【问题描述】:

我的Student 类中有一个私有变量,定义为:

const int studentNumnber;

我正在尝试为 Student 编写一个复制构造函数,我需要抛弃 constness 来执行此操作。不幸的是,我不明白如何使用std::const_cast。

这就是我在复制构造函数中尝试做的事情:

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

这不起作用...我不确定语法。

【问题讨论】:

    标签: c++ const-cast


    【解决方案1】:

    在您的代码中,您尝试强制转换此指针而不是变量。您可以尝试以下方法:

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

    【讨论】:

      【解决方案2】:

      你不能const_cast实际上是const的变量。这会导致未定义的行为。 const_cast 用于从最终引用非 const 的引用和指针中删除 const-ness。

      所以,这是允许的:

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

      这是允许的,因为分配给的对象 i 不是 const。以下是不允许的:

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

      因为这里 i 是 const 并且您正在通过为其分配一个新值来对其进行修改。代码会编译,但它的行为是不确定的(这可能意味着从“它工作得很好”到“程序会崩溃”。)

      您应该在构造函数的初始化器中初始化常量数据成员,而不是在构造函数体中分配它们:

      Student(const Student & s) 
          : Person(p.getName(), p.getEmailAddress(), p.getBirthDate()),
            school(0),
            studentNumber(s.studentNumber)
      {
          // ...
      }
      

      【讨论】:

      • "你应该初始化数据成员..." 而不仅仅是 const 数据
      • 从 实际上(已定义)const 的对象中丢弃 const 的部分是不允许的? 演员本身,还是后续的修改?
      • “你不能对实际上是 const 的变量进行 const_cast” 这不是真的。写入这样的变量具有未定义的行为,但转换本身是 100% 合法的(但这是一个坏主意,因为它创造了到达所述 UB 的可能性!)
      • 请参阅 stackoverflow.com/a/54504302/9204 以确认此答案是错误的。
      • 如果语言有const_cast 会导致未定义的行为,那么它的意义何在?没有意义。
      猜你喜欢
      • 1970-01-01
      • 2019-08-03
      • 2012-12-01
      • 2012-12-25
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-10
      • 1970-01-01
      相关资源
      最近更新 更多