Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

const_cast trong C++ - Toán tử ép kiểu

const_cast là một trong các toán tử ép kiểu (casting operators) của C++. Dùng để thêm hoặc bỏ qualifier const/volatile của kiểu dữ liệu.

Cú pháp

const_cast<new_type>(expression)

new_type phải trùng kiểu với expression trừ qualifier const/volatile.

Ví dụ: Bỏ const của con trỏ

#include <iostream>
using namespace std;

int main() {
    const int a = 20;
    const int* b = &a;
    cout << "old value: " << *b << "\n";
    
    int* c = const_cast<int*>(b);
    *c = 40;
    
    cout << "new value: " << *b;
    return 0;
}

Kết quả

old value: 20
new value: 40

Các casting operators khác trong C++

Toán tửMục đích
static_castÉp kiểu tĩnh, an toàn tại compile-time
dynamic_castÉp kiểu đa hình, kiểm tra runtime (cần RTTI)
const_castThêm/bỏ const/volatile
reinterpret_castÉp kiểu cấp thấp, reinterpret bit pattern

Khi nào dùng const_cast?

  • Tương tác với API cũ (legacy) không const-correct.
  • Triển khai logic const-phân biệt (const-overload) tránh lặp code.
  • KHÔNG dùng để sửa đối tượng thực sự const (hằng số, literal, biến const) → UB.

Ví dụ an toàn: const-overload

class TextBlock {
    string text;
public:
    const char& operator[](size_t pos) const { return text[pos]; }
    char& operator[](size_t pos) {
        return const_cast<char>(static_cast<const TextBlock>(*this)[pos]);
    }
};

Non-const version gọi const version qua const_cast, tránh lặp logic.